c++ - 在模板化类中定义模板化类的静态数据成员

标签 c++ templates c++14

我在另一个类模板中有一个类模板。内部类有一个静态数据成员。我正在努力为它提供一个定义。以下示例适用于 clang 3.8 但不适用于 gcc-7.1

template <typename T>
struct Out {
  template <typename U>
  struct In {
    static int var;
  };
};

template <typename T>
template <typename U>
int Out<T>::template In<U>::var;

gcc 给出错误:

error: template definition of non-template ‘int Out<T>::In<U>::var’
 int Out<T>::template In<U>::var;
                             ^~~

我该怎么做才能让 gcc 开心?


编辑:结果是摆脱了 template 让这个工作:

template <typename T>
template <typename U>
int Out<T>::In<U>::var;

还有一个问题,template 在这里允许吗?

最佳答案

如果没有 template,这种类型的定义会更常见。之前 In . template这里不需要关键字,因为 Out<T>::In是“当前特化的成员”。

对于指定何时 template 的规则成员名称前需要关键字,请参阅 [temp.names]/4。对于技术术语“当前特化的成员”的定义,请参见 [temp.dep.type]/4。

但事实上关键字在那里是允许的,因为语法允许它在任何 :: 之间。和名称,语义只要求后面的名称与模板参数一起使用或命名为类模板 ([temp.names]/5),并且标准中没有其他规则禁止它。正如 [temp.names]/5 中的注释所解释的那样:

[ Note: As is the case with the typename prefix, the template prefix is allowed in cases where it is not strictly necessary; i.e., when the nested-name-specifier or the expression on the left of the -> or . is not dependent on a template parameter, or the use does not appear in the scope of a template. - end note]

关于c++ - 在模板化类中定义模板化类的静态数据成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46574697/

相关文章:

对象或静态中的 C++ 方法

c++ - 在 C++ 代码中查找非实例化模板

c++ - 找出仿函数 C++11\Boost 的返回类型

c++ - 我可以将 C++17 无捕获 lambda constexpr 转换运算符的结果用作函数指针模板非类型参数吗?

c++ - 在 C++ 中使用在其他文件中声明的模板

C++ 映射将所有键的值显示为 0

c++ - 从用户那里获得N号并找到最大的

c++ - c++中列表的接口(interface)

c++ - 我可以在 C++ 中部分编译模板函数吗

c++ - 结构指针函数指向其他结构的其他函数