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