请注意,有代码 sn-p 对 添加的关键字和 未 添加的关键字都有效,在每种情况下都会产生不同的结果,即使对于采用类型参数而不是整数的模板也是如此。
#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;
}
在没有添加 template 关键字的情况下运行时输出 0。如果在f < int() > 之前添加关键字,则会输出1。
说明
没有关键字的版本解析为
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;
注意temp2 是一个空指针(由return T() 产生)。完全不同的解析,两者都是有效的!这确实需要一种消除歧义的方法——即在适当的时候插入template 关键字。