2017-03-16 461 views
7

我遇到了一個奇怪的情況,我的派生類能夠訪問其基類的私有成員,其中包含模板。派生類可以訪問其基類的私有成員


考慮這個例子:

class A 
{ 
    template<typename T> 
    struct a { using type = a; }; 
}; 

class B : A 
{ 
    template<typename T> 
    using type = typename a<T>::type; 
}; 

int main(){ } 

編譯結果:

mingw64 /的mingw-W64-x86_64的-鐺3.9.1-3(從MSYS2)

$ clang++ -Wall test.cpp -o test.exe -std=c++14 

mingw64/mingw-w64-x86_64-gcc 6.3.0-2(來自MSYS2)

$ g++ -Wall test.cpp -o test.exe -std=c++14 

兩種編譯器接受沒有錯誤!此外,如果您只需要移動B::type成類似B::b::type鐺突然意識到它不應該被訪問的私有成員,而G ++沒有問題,編譯:

class A 
{ 
    template<typename T> 
    struct a { using type = a; }; 
}; 

class B : A 
{ 
    template<typename T> 
    struct b { using type = typename a<T>::type; }; 
}; 

int main(){ } 

編譯結果

mingw64/mingw- W64-x86_64的-鐺3.9.1-3(從MSYS2)

$ clang++ -Wall test.cpp -o test.exe -std=c++14 
test.cpp:10:39: error: 'a' is a private member of 'A' 
     struct b { using type = typename a<T>::type; }; 
             ^
test.cpp:4:13: note: implicitly declared private here 
     struct a { using type = a; }; 
      ^
1 error generated. 

mingw64 /的mingw-W64-x86_64的-GCC 6.3.0-2(從MSYS2)

$ g++ -Wall test.cpp -o test.exe -std=c++14 

我的問題是,是什麼原因造成這種現象,其中一個派生類,有時可以訪問其基類的成員,有時不能,而這是預期的行爲?

回答

9

我的問題是,什麼導致這種行爲,其中派生類有時有權訪問其基類的成員,有時不會,這是預期的行爲?

一個編譯器錯誤。有一堆gcc bugs與模板中的訪問控制相關,這個可能是由#41437專門解決的。鐺別名模板錯誤是#15914

相關問題