c++的bad_cast异常将*this强制转换为派生模板类

C++ bad_cast exception casting *this to derived template class

本文关键字:转换 派生 this bad cast 异常 c++      更新时间:2023-10-16

我正在尝试虚拟模板函数实现。当将this指针转换为指向子类模板的指针时,我让它工作,但是当我将*this转换为引用子类时,我无法让它工作,为什么?

template <typename T> struct BB; // forward reference (not bound until instantiation in main)
struct AA
{
    virtual ~AA(){}
    template <typename T>
    void operator()(T && t)
    {
        dynamic_cast<BB<T>*>(this)->operator()(std::forward<T>(t)); // works!
        dynamic_cast<BB<T>&>(*this)(std::forward<T>(t));            // compiles but throws bad_cast
    }
};
template <typename T>
struct BB : AA
{
    void operator()(T t) { std::cout << "BB::operator()" << std::endl; }
};
int main()
{
    BB<int> bb;
    int k = 5;
    static_cast<AA&>(bb)(k);
}

在您的调用static_cast<AA&>(bb)(k);中,T被推导为int &,并且包含*this的最派生对象不是BB<int &>类型。所以这两个类型转换都失败了,指针间接地产生了未定义的行为。