简体   繁体   中英

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

I am attempting a virtual template function implementation. I have it working when casting this pointer to a pointer to subclass template, but I cannot get it to work when I cast *this to reference to subclass, why?

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);
}

In your call static_cast<AA&>(bb)(k); , T is deduced as int & , and the most-derived object containing *this is not of type BB<int &> . So both casts fail, and your pointer indirection produces undefined behaviour.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM