我在另一个类模板中有一个类模板。内部类有一个静态数据成员。我正在努力为它提供一个定义。以下示例适用于 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, thetemplate
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/