这不编译:
template<class X> struct A {
template<int I> void f() {}
};
template<class T> void g()
{
A<T> a;
a.f<3>(); // Compilation fails here (Line 18)
}
int main(int argc, char *argv[])
{
g<int>(); // Line 23
}
Run Code Online (Sandbox Code Playgroud)
编译器(gcc)说:
hhh.cpp:在函数'void g()'中:
hhh.cpp:18:错误:')'令牌之前的预期primary-expression
hhh.cpp:在函数'void g()[with T = int]'中:
hhh.cpp:23:从这里实例化
hhh.cpp:18:错误:无效使用成员(你忘了'&'?)
谁能解释为什么会这样?有没有办法让它发挥作用?
Kir*_*sky 78
请尝试以下代码:
template<class T> void g()
{
A<T> a;
a.template f<3>(); // add `template` keyword here
}
Run Code Online (Sandbox Code Playgroud)
根据C++'03标准14.2/4:
当一个构件模板特的名称出现之后
.
或->
在一个后缀 -expression或之后嵌套名称说明符在一个合格-ID,和后缀表达或合格-ID明确地依赖于模板参数(14.6.2 ),成员模板名称必须以关键字为前缀template
.否则,假定该名称命名非模板.
根据草案n2857 14.3/4,未来的C++标准似乎仍然需要这个关键字.一些编译器具有允许编译原始代码而没有错误的特殊模式(Comeau在所谓的宽松模式下编译它).