次のコードは、g++ 4.6.1 でコンパイルできません。
template<class Base>
struct GetBase {
Base * getBase() {
return static_cast<Base *>(this);
}
};
template<class Derived>
struct Parent : private GetBase<Derived> {
using GetBase<Derived>::getBase;
int y() {
return getBase()->x();
}
};
struct Child : public Parent<Child> {
int x() {
return 5;
}
int z() {
return y();
}
};
エラーで
In member function ‘Base* GetBase<Base>::getBase() [with Base = Child]’:
instantiated from ‘int Parent<Derived>::y() [with Derived = Child]’
instantiated from here
error: ‘GetBase<Child>’ is an inaccessible base of ‘Child’
static_cast を reinterpret_cast に変更すると、コードがコンパイルされ、この場合は機能しますが、これがすべての場合に受け入れられる解決策であるかどうか疑問に思っていますか? つまり、基本クラスへのポインターがこれと同じでない場合はありますか? 親にデータメンバーがある場合、多重継承でこれが発生する可能性があると思いますか? GetBase が最初のスーパークラスである場合、this ポインターは等しいことが保証されていますか?