【发布时间】:2021-02-09 20:48:08
【问题描述】:
在previous post 中关注关于向下转换和类型安全的类似问题,我想知道以下示例是否会创建未定义的行为。
已创建 Base 类的实例。不发生动态绑定。
但是,在 Base::interface 函数中, Base 类的实例被强制转换为 Derived 类的实例。
这安全吗?如果是,为什么?
请在下面找到这段代码。
#include <iostream>
template <typename Derived>
struct Base{
void interface(){
static_cast<Derived*>(this)->implementation();
}
};
struct Derived1: Base<Derived1>{
void implementation(){
std::cout << "Implementation Derived1" << std::endl;
}
};
int main(){
std::cout << std::endl;
Base<Derived1> d1;
d1.interface();
std::cout << std::endl;
}
【问题讨论】: