2010-06-16 35 views

回答

16

依賴名被用來指一個嵌套模板,嵌套的名稱必須與關鍵字template幫助編譯器預先考慮明白,你指的是一個嵌套的模板,並正確地解析代碼

template <typename T> 
void F(A<T> &a) 
{ 
    a.template f<0>(); 
} 

裏面main名稱a是不依賴的,這就是爲什麼你不需要額外template關鍵字。裏面F名稱a是依賴的,這就是爲什麼需要關鍵字。

這與通過從屬名稱引用嵌套類型名稱時的額外typename關鍵字類似。只是語法略有不同。

1

在前者中,編譯器認爲你的意思是......

a.f < 0 ...gibberish.... 

安德烈的回答解決了。

0

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

#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關鍵字。