簡體   English   中英

C ++ bad_cast異常強制轉換*這到派生模板類

[英]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 &>類型。 因此,這兩個強制轉換都將失敗,並且指針間接產生未定義的行為。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM