以下代码无法在 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 将使代码编译并且在这种情况下它会起作用,但我想知道这是否在所有情况下都是可接受的解决方案?即,指向基类的指针是否与此不同?我假设如果 parent 有数据成员,多重继承可能会发生这种情况?如果 GetBase 是第一个父类(super class),那么 this 指针是否保证相等?
最佳答案
我想知道这是否在所有情况下都是可接受的解决方案?
否。(见下文)
指向基类的指针是否与此不同?
是的。
对于多重继承,不能期望基类具有相同的地址。
根据编译器的不同,带有 vtable 指针的派生类可能与没有 vtable 指针的基类具有相同的
this
。
当显式向上转换为基类时,static_cast
是合适的 C++ 转换。
关于c++ - 问题重构奇怪地重复出现的模板模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8978260/