ときどき、C++ のプライバシーの概念に当惑することがあります :-)
class Foo
{
struct Bar;
Bar* p;
public:
Bar* operator->() const
{
return p;
}
};
struct Foo::Bar
{
void baz()
{
std::cout << "inside baz\n";
}
};
int main()
{
Foo::Bar b; // error: 'struct Foo::Bar' is private within this context
Foo f;
f->baz(); // fine
}
Foo::Bar
ですので、private
では宣言できません。それでも、問題なくメソッドを呼び出すことができます。なんでこんなの許されるの?それは偶然ですか、それとも意図的なものですか?b
main
Foo::Bar
ちょっと待ってください。
Foo f;
auto x = f.operator->(); // :-)
x->baz();
type に名前を付けることは許可されていませんが、 ...Foo::Bar
で問題なく動作します。auto
ノアは次のように書いています。
クラス定義内で定義された型名は、修飾せずにクラス外で使用することはできません。
楽しみのために、外部から型を取得する方法を次に示します。
#include <type_traits>
const Foo some_foo();
typedef typename std::remove_pointer<decltype( some_foo().operator->() )>::type Foo_Bar;