我想知道的是:
- 此代码段是否可移植?
- 如果不是,为什么?
struct GenericBase{
};
struct MyObject : public GenericBase{
virtual void method() = 0;
};
struct MyAlias : public MyObject{
//supposed to have exactly the same layout as MyObject (?)
};
struct MyImpl : public MyObject{
virtual void method() { cout << "method implementation \n"; }
//note that MyImpl inherit MyObject, but we cast it to MyAlias
};
void test_alias(){
MyImpl m;
GenericBase* ptr = &m;
MyAlias* new_ptr = static_cast<MyAlias*>(ptr); //here is the cast
new_ptr->method();
}
编辑:
我不能使用 RTTI,也不能使用模板
最佳答案
回答:这不是可移植的。
struct MyAlias : public MyObject{
//supposed to have exactly the same layout as MyObject (?)
};
这个评论是错误的:MyAlias 的大小是依赖于实现的,并且不是由标准指定的(例如,它取决于目标体系结构的对齐要求:编译器可能会在派生对象中添加填充位,或者关于如何实现方法调度等。)
关于c++ - 某种类型别名 : An empty derived class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24148422/