template member function of template class called from template function
这不编译:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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: In function 'void g()':
hhh.cpp:18: error: expected primary-expression before ')' token
hhh.cpp: In function 'void g() [with T = int]':
hhh.cpp:23: instantiated from here
hhh.cpp:18: error: invalid use of member (did you forget the '&' ?)
有人能解释这是为什么吗?有办法让它工作吗?
尝试以下代码:
1 2 3 4 5 | template<class T> void g() { A<T> a; a.template f<3>(); // add `template` keyword here } |
根据C++03标准142/4:
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++标准似乎仍然需要这个关键字根据草案N2557 143/4。有些编译器有特殊的模式,允许编译原始代码而不出错(comeau以所谓的宽松模式编译它)。