以下代码无法在 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 指针相等?