(如果您已经知道答案,这个问题只是另一个问题的重复!)
(请注意我的后续问题:如果存在同名的不相关的全局模板函数,为什么不需要模板关键字? https://stackoverflow.com/questions/23892498/why-is-no-template-keyword-needed-if-an-unrelated-global-template-function-with)
当我尝试使用以下结构编译模板化 C++ 代码时,在指定行出现编译器错误:
template <int N>
struct A {
template <int i>
void f() {};
};
template <int N>
struct B {
A<N> a;
B(A<N>& a) : a(a) {}
void test() {
a.f<1>(); // does not compile
}
};
int main() {
A<2> a;
a.f<1>(); // works fine
B<2> b(a);
b.test();
}
g++
says:
test2.cpp: In member function ‘void B<N>::test()’:
test2.cpp:14: error: expected primary-expression before ‘)’ token
test2.cpp: In member function ‘void B<N>::test() [with int N = 2]’:
test2.cpp:22: instantiated from here
test2.cpp:14: error: invalid operands of types ‘<unresolved overloaded function type>’ and ‘int’ to binary ‘operator<’
clang++
says:
test2.cpp:14:16: error: expected expression
a.f<1>(); // does not compile
^
1 error generated.
相同的表达方式适用于main()
,但不在test()
模板类的方法B
,其中有一个实例A
作为私有变量。我很不明白为什么这不起作用。
你必须使用a.template f<1>();
代替b.test()
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)