c++ - 为什么在 `template` 类的枚举上使用声明不起作用?

标签 c++ enums scope

编译:

template <typename T> class Parent { public:
  enum MyEnum { RED,GREEN,BLUE };
};
class Child : public Parent<int> { public:
  using Parent<int>::MyEnum;
  int foo() { return GREEN; }
};
void tester() { Child d; d.foo(); }

这不是(在 gcc 上,输出 error: 'GREEN' was not declared in this scope):

template <typename T> class Parent { public:
  enum MyEnum { RED,GREEN,BLUE };
};
template <typename T> class Child : public Parent<T> { public:
  using Parent<T>::MyEnum;
  int foo() { return GREEN; }
};
void tester() { Child<int> d; d.foo(); }

我的问题:为什么?(另外,有什么解决方法的建议吗?)

最佳答案

对于第二个代码:

  1. 您需要添加 typename 关键字,因为您访问的类型 MyEnum 依赖于 T。将 using 行更改为:

using typename Parent<T>::MyEnum;

  1. 然后,在方法foo您需要像这样指定 GREEN 是枚举 MyEnum 的成员:

int foo() { return MyEnum::GREEN; }

用 gcc 编译对我来说很好,用 C++11 编译得很好
实例here

它在第一个示例中起作用,因为 using 行中的 MyEnum 不依赖于模板类型 T。您明确使用了 int 类型的 Parent。

关于c++ - 为什么在 `template` 类的枚举上使用声明不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31602332/

相关文章:

c++ - 如何重新创建树,其中序遍历存储在文件中

c++ - OpenCV:读取矩阵值

Java:使用反射实例化枚举

java - 设置其他方法识别的变量

javascript - 为什么 'this' 突然超出了我的范围?

c - 当字符串位于数组中时,如何从函数返回字符串

C++ std::make_shared 内存泄漏

Java Maven 编译错误 "Unable to read class",其中包含枚举

python - 如何禁用 python 枚举中的某些项目,但不删除它们

C++ 程序不能完全读取大量输入。为什么?