C++ bad_cast 将 *this 异常转换为派生模板 class

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

我正在尝试虚拟模板函数实现。我在将 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 &> 类型。所以两个转换都失败了,你的指针间接产生了未定义的行为。