我对以下形式的一段代码有疑问:
template<class Type>
class Class1 {
public:
template<class TypeName1> TypeName1* method1() const {return 0;}
};
struct Type1{};
struct Type2{};
class Class2 {
public:
template<typename TypeName1, typename TypeName2>
int method2() {
Class1<TypeName2> c;
c.method1<TypeName1>();
return 0;
}
int method1() {
return method2<Type1, Type2>();
}
};
int
main() {
Class2 c;
return c.method1();
}
在键盘上用编译器编译时:
我收到以下错误:
t.cpp: In member function 'int Class2::method2()': Line 15: error: expected primary-expression before '>' token compilation terminated due to -Wfatal-errors.
违规行是模板成员函数的调用:
c.method1<TypeName1>();
最佳答案
您应该使用 template
当您调用成员函数模板并且您有依赖名称时的关键字,或 method1
会被解析为c
的成员变量和 <
作为“小于”符号:
c.template method1<TypeName1>();
正如@DrewDormann 正确指出的,template
的原因需要关键字是 Class1
的特化提供的特定类型参数可以存在类模板,其中 method1
被定义为成员变量而不是函数模板。因此,必须明确指示编译器解析 method1
如果不是这种情况,则作为函数模板的名称。
关于c++ - 调用模板成员函数编译失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14811589/