注意到有是代碼段是有效的兩者添加的關鍵字和不加入,得到在每種情況下不同的結果,即使對於採取類型參數而不是整數的模板。
#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
關鍵字。