use*_*299 3 c++ compiler-errors g++ clang++
我正在尝试使用g ++编译一些Microsoft Visual C++代码.现在我遇到了一个我真的无法理解的编译器错误.(简化)代码如下所示:
template<int X> struct A {
template<class Ret> static Ret call() {
return 0;
}
};
template<int X> struct B : A<X> {
int f() {
return A<X>::call<int>();
}
};
Run Code Online (Sandbox Code Playgroud)
当我尝试用g ++(版本4.4.5)编译它时,我收到以下错误:
main.cpp: In member function int B<X>::f():
main.cpp:16: error: expected primary-expression before int
main.cpp:16: error: expected ; before int
main.cpp:16: error: expected unqualified-id before > token
Run Code Online (Sandbox Code Playgroud)
如果我从方法A :: call中删除模板类型(Ret),代码编译就好了.任何人都可以看到这里有什么不对吗?
谢谢!
你需要template关键字:
return A<X>::template call<int>();
Run Code Online (Sandbox Code Playgroud)
call是一个依赖名称,这意味着它的表示取决于模板参数,这在编译器进程时是未知的f().您需要call通过在其前面加上template关键字来表明它是一个函数模板.
当您尝试访问嵌套类型时会发生同样的事情:您需要添加typename关键字以指示名称表示类型:
template <typename T>
struct A { typedef int type; };
template <typename T>
void f()
{
typename A<T>::type i = 0; // notice "typename" here
}
Run Code Online (Sandbox Code Playgroud)
有时你甚至需要混合两者:
template <typename T>
struct A
{
template <typename U>
struct inner { };
};
template <typename T>
void f()
{
typename A<T>::template inner<int> var;
}
Run Code Online (Sandbox Code Playgroud)
在这个问题的答案中详细解释了这两个关键字的使用:我必须在何处以及为什么要使用"模板"和"typename"关键字?(感谢@BjörnPollex寻找链接).
A是一个模板,并且不知道X编译器无法确定内容A<X>.特别是它不知道call最终会成为一个模板.
要告诉编译器你必须使用template关键字:
template<int X> struct B : A<X> {
int f() {
return A<X>::template call<int>();
}
};
Run Code Online (Sandbox Code Playgroud)