从模板函数调用的模板类的C ++模板成员函数 [英] C++ template member function of template class called from template function
问题描述
这不编译:
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
}
编译器(gcc)说:
hhh.cpp:在函数'void g()':
hhh.cpp: In function 'void g()':
hhh.cpp:18 :错误:期望的主表达式之前')'令牌
hhh.cpp:18: error: expected primary-expression before ')' token
hhh.cpp:在函数'void g()[with T = int]':
hhh.cpp: In function 'void g() [with T = int]':
hhh.cpp:23:从这里实例化
hhh.cpp:23: instantiated from here
hhh.cpp:18:错误:忘记&'?)
hhh.cpp:18: error: invalid use of member (did you forget the '&' ?)
任何人都可以解释为什么会这样?是否有办法让它工作?
Can anyone explain why this is? Is there a way to get it to work?
编辑:添加了main()和编译器错误。
Added main() and the compiler error.
推荐答案
尝试以下代码:
template<class T> void g()
{
A<T> a;
a.template f<3>(); // add `template` keyword here
}
根据C ++'03 Standard 14.2 / 4:
According to C++'03 Standard 14.2/4:
成员模板专用化的名称出现在
。
在后缀表达式中或在 qualified-id中的 nested-name-specifier 之后的 code> - > ,且postfix-expression或qualified-id显式取决于模板参数(14.6.2),成员模板名称必须以关键字template
。
When the name of a member template specialization appears after
.
or->
in a postfix-expression, or after nested-name-specifier in a qualified-id, and the postfix-expression or qualified-id explicitly depends on a template-parameter (14.6.2), the member template name must be prefixed by the keywordtemplate
. Otherwise the name is assumed to name a non-template.
未来C ++标准似乎仍需要此关键字根据草案n2857 14.3 / 4。一些编译器有特殊的模式,允许编译原始代码没有错误(Comeau编译它在所谓的宽松模式)。
Future C++ Standard seems to be still require this keyword according to draft n2857 14.3/4. Some compilers has special mode that allows to compile original code without errors (Comeau compiles it in so called relaxed mode).
这篇关于从模板函数调用的模板类的C ++模板成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!