c++ - 前向声明类模板的成员枚举

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

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

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 模板,其中第一段指出:

The declaration in a template-declaration shall

  • declare or define a function or a class, or
  • define a member function, a member class, a member enumeration, or a static data member of a class template or of a class nested within a class template, or
  • define a member template of a class or class template, or
  • be an alias-declaration.

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

最佳答案

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

An enumeration member of a class template may be defined outside the class template definition. [ Example:

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;

—end example ]

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

关于c++ - 前向声明类模板的成员枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22453111/

相关文章:

c++ - 在 Qt 中围绕 QWidget 拖动对象

c++ - 在构造函数调用中出现错误 C2512

c++ - 使用 "extern template"时专门化模板的正确方法是什么?

c++ - 如何用父类型的智能指针调用子类的析构函数?

c++ - 错误 C2143 和错误 C2059 在 ";"之前缺少 "{"

c++ - 为什么共享锁只能持有一把可升级锁

c++ - 派生类中的析构函数标记为 noexcept(false)

html - 如何在模板 Jinja2 的同一对象上添加类和其他 HTML 属性?

c++ - 定义 static constexpr auto 类变量

c++ - 标准库中没有 std::identity 是有原因的吗?