簡體   English   中英

std :: reference_wrapper和多態容器

[英]std::reference_wrapper and polymorphic containers

我正在嘗試使用std::reference_wrapper為這些類創建多態向量:

struct Int2TypeBase{
    virtual void which(){ std::cout << "Int2TypeBase" << "\n";}
};


template <int v>
struct Int2Type : public Int2TypeBase
{
    enum
    {
        value = v
    };

    void which(){ std::cout << "Int2Type<" << value  << ">""\n";}

    friend bool operator==(const Int2Type& lhs, const Int2Type& rhs){
        return lhs.v == rhs.v;
    }
};

現在,我試圖像這樣使用std::reference_wrapper

int main(){
    using namespace std;

    std::vector<std::reference_wrapper<Int2TypeBase>> v;

    Int2Type<0> i2t_1;
    v.emplace_back(i2t_1);

    auto x = v[0];
    x.get().which();

    std::cout << typeid(x.get()).name() << "\n";

    // std::cout << (x.get() == i2t_1) << "\n";
}

輸出為:

Int2Type<0>
8Int2TypeILi0EE

這就是我所期望的。

現在,當我取消注釋std::cout << (x.get() == i2t_1) << "\\n"; 我會得到

invalid operands to binary expression ('Int2TypeBase' and 'Int2Type<0>')

這讓我感到困惑,因為typeid(x.get()).name()返回了8Int2TypeILi0EE而不是F12Int2TypeBasevE ,這就是我獲得的typeid(Int2TypeBase()).name(); 此外which()也被稱為派生類的......那么,為什么不x.get()x.get() == i2t_1計算為Int2TypeBase

您的比較運算符僅為派生類定義,但是引用包裝器生成(靜態)類型Int2Base ,因此重載解析甚至找不到您的比較運算符!

您可能需要的是表單的比較運算符

bool operator==(const Int2TypeBase& lhs, const Int2TypeBase& rhs)

但是您還需要進行某種多態調度以執行實際比較(大概假設動態類型匹配)。

在編譯時,編譯器只能告訴x.get()的類型為Int2TypeBase,因為如聲明的那樣,您可以在其中放置任何Int2TypeBase。 因此,在編譯時,無法確定==運算符是否可以工作。

在運行時,您放入集合中的對象將引用其完整類型,因此typeid返回您期望的值,並調用正確的虛函數。

暫無
暫無

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

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