派生 class 能够访问其基础 class' 私有成员
Derived class is able to access its base class' private member
我 运行 遇到了一个奇怪的情况,我的派生 class 能够访问其基础 class 的私有成员,其中涉及模板。
考虑这个例子:
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-clang 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
之类的地方,clang 会突然意识到它不应该访问私有成员,而 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-clang 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
我的问题是,派生的 class 有时可以访问其基础 class 成员,有时却不能访问的行为是什么导致的,这是预期的行为吗?
My question is, what is causing this behavior where a derived class sometimes has access to its base class' members, and sometimes does not, and is this expected behavior?
编译器错误。有一堆 gcc bugs related to access control in templates, this one is probably specifically address by #41437. The clang alias template bug is #15914.
我 运行 遇到了一个奇怪的情况,我的派生 class 能够访问其基础 class 的私有成员,其中涉及模板。
考虑这个例子:
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-clang 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
之类的地方,clang 会突然意识到它不应该访问私有成员,而 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-clang 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
我的问题是,派生的 class 有时可以访问其基础 class 成员,有时却不能访问的行为是什么导致的,这是预期的行为吗?
My question is, what is causing this behavior where a derived class sometimes has access to its base class' members, and sometimes does not, and is this expected behavior?
编译器错误。有一堆 gcc bugs related to access control in templates, this one is probably specifically address by #41437. The clang alias template bug is #15914.