C++ 奇怪的GCC';预期的主表达式…';错误
可能重复:C++ 奇怪的GCC';预期的主表达式…';错误,c++,templates,gcc,C++,Templates,Gcc,可能重复: 模板 结构A { 模板 无效f(); }; 模板 无效F(A&A) { a、 f();//在“')标记之前应为主表达式 } int main() { A A; a、 f();//这个没问题。 } 这是关于什么的?当使用依赖名称引用嵌套模板时,嵌套名称必须在关键字template前面加上关键字,以帮助编译器理解您引用的是嵌套模板并正确解析代码 template <typename T> void F(A<T> &a) { a.template
模板
结构A
{
模板
无效f();
};
模板
无效F(A&A)
{
a、 f();//在“')标记之前应为主表达式
}
int main()
{
A A;
a、 f();//这个没问题。
}
这是关于什么的?当使用依赖名称引用嵌套模板时,嵌套名称必须在关键字template
前面加上关键字,以帮助编译器理解您引用的是嵌套模板并正确解析代码
template <typename T>
void F(A<T> &a)
{
a.template f<0>();
}
模板
无效F(A&A)
{
a、 模板f();
}
在main
内部,名称a
是不相关的,这就是为什么不需要额外的模板
关键字的原因。内部F
namea
是依赖的,这就是需要关键字的原因
当通过依赖名称引用嵌套类型名称时,这类似于额外的
typename
关键字。只是语法略有不同。在前者中,编译器认为您的意思是
a.f < 0 ...gibberish....
a.f<0……胡言乱语。。。。
Andrey的回答解决了这一问题。请注意,有些代码片段对添加的关键字和未添加的关键字都有效,在每种情况下都会产生不同的结果,即使对于采用类型参数而不是整数的模板也是如此
#include <iostream>
struct A {
template<typename T>
static A f(T) {
return A();
}
template<typename T> operator T() { return T(); }
};
template<typename U>
int g() {
U u;
typedef A (*funcPtrType)(int());
return !(funcPtrType)u.f < int() > (0);
}
int main() {
std::cout << g<A>() << std::endl;
}
带有关键字的版本解析为
funcPtrType temp1 = (funcPtrType)u.f; // taking func address
bool temp2 = !temp1; // temp2 == false
bool temp3 = temp2 < int(); // temp3 == false
bool temp4 = temp3 > (0); // temp4 == false
return temp4;
A temp1 = u.template f < int() > (0); // function call
funcPtrType temp2 = (funcPtrType) temp1; // temp2 == 0
bool temp3 = !temp2; // temp3 == true
return temp3;
A temp1=u.template f(0);//函数调用
funcPtrType temp2=(funcPtrType)temp1;//temp2==0
bool temp3=!temp2;//temp3==true
返回temp3;
请注意,temp2
是一个空指针(由returnt()
生成)。完全不同的解析,两者都是有效的!这确实需要一种消除歧义的方法,即根据需要插入模板
关键字
A temp1 = u.template f < int() > (0); // function call
funcPtrType temp2 = (funcPtrType) temp1; // temp2 == 0
bool temp3 = !temp2; // temp3 == true
return temp3;