2010-04-29 59 views
6

我試圖使用模板化基類的成員變量在派生類,如在此示例中:使用成員變量

template <class dtype> 
struct A { 
    int x; 
}; 

template <class dtype> 
struct B : public A<dtype> { 
    void test() { 
     int id1 = this->x;  // always works 
     int id2 = A<dtype>::x; // always works 
     int id3 = B::x;   // always works 
     int id4 = x;   // fails in gcc & clang, works in icc and xlc 
    } 
}; 

gcc和鐺都是對使用這個變量非常挑剔,並且需要明確的範圍或明確使用「this」。與其他一些編譯器(xlc和icc)一樣,事情按我的預期工作。這是xlc和icc的一種情況,它允許不符合標準的代碼或gcc和clang中的錯誤?

+1

相似問題:http://stackoverflow.com/questions/11405/gcc-problem-using-a-member-of-a-base-class-that-depends-on-a-template-argument – 2010-04-29 16:29:25

回答

5

您可能正在編譯icc中的非嚴格模式。無論如何,因爲x是不合格的,所以不能在任何依賴於模板參數的基類中查找。因此,在您的代碼中,沒有找到x的地方,而且您的代碼無效。

使用其他形式的查找(類成員訪問查找和合格查找)查找其他名稱。如果可能的話,這兩種形式都會查看相關的基類(即,如果它們是從屬的,並且在dtype已知的情況下實例化模板時查找 - 所有其他名稱都依賴於模板參數)。

即使GCC在其最新版本中也沒有正確實現,並且在非限定查找過程中會使用一些依賴名稱still resolve against dependent bases