【问题标题】:Forward-declare a member enumeration of a class template前向声明类模板的成员枚举
【发布时间】:2014-04-22 14:01:14
【问题描述】:

使用 C++11 的强类型 enums,可以像这样声明一个类的成员枚举:

class X {
public:
    enum class E;
};

enum class X::E { a, b };

但是,当将X 设为类模板时:

template <typename T>
class X {
public:
    enum class E;
};

template <typename T>
enum class X<T>::E { a, b };

gcc 4.7.2 和 clang 3.0 都分别抱怨“错误:'enum X::E' 是一个枚举模板 [-pedantic]”和“错误:枚举不能是一个模板”。我认为相关的标准部分(事实上,这个问题源于此)是§14 Templates,其中第一段指出:

模板声明中的声明

  • 声明或定义函数或类,或
  • 定义成员函数、成员类、成员枚举类模板的静态数据成员或嵌套在类模板,或
  • 定义类或类模板的成员模板,或
  • 是一个别名声明

(强调我的)。那么这是一个编译器错误,还是我完全误解了该语句?

【问题讨论】:

  • gcc 4.8.1 仍然考虑it is an error,而clang 3.4 does not
  • 使用 gcc 4.8.2 编译。
  • @evnu 即使有-pedantic-errors 编译器标志?
  • @Constructor 我的错,我忘记了参数。不,它也会发出警告。
  • @Constructor:是的,这看起来很有希望。想要发布它作为答案?

标签: c++ templates c++11 enums forward-declaration


【解决方案1】:

有人要求我创建这个答案。请参阅 C++ 标准的 [temp.mem.enum] 14.5.1.4/1 段:

类模板的枚举成员可以在 类模板定义。 [ 例子:

template<class T> struct A {
  enum E : T;
};
A<int> a;
template<class T> enum A<T>::E : T { e1, e2 };
A<int>::E e = A<int>::e1;

——结束示例 ]

较新版本的 clang (3.4) compiles your code successfully 带有标志 -pedantic-errorsgcc 4.8.1 still considers it is an error。我认为这是一个 gcc 错误。

【讨论】:

  • 好吧,这就解决了。可能应该进一步阅读......感谢您的努力!
猜你喜欢
  • 2023-03-27
  • 1970-01-01
  • 2011-11-20
  • 1970-01-01
  • 1970-01-01
  • 2013-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多