簡體   English   中英

操作符不匹配*使用boost :: variant時

[英]No match for operator * when using boost::variant

我定義自己的variant類型,如下所示:

typedef variant<myobj **, ... other types> VariantData;

我的一種類方法將這種數據類型作為參數,並嘗試執行以下操作:

void MyMethod(VariantData var){
    //method body
    if(some_cond){ // if true, then it implies that var is of type
                   // myobj **
        do_something(*var); // however, I'm unable to dereference it
    }
    // ... ther unnecessary stuff
}

結果,當我編譯程序時,出現以下錯誤消息:

error: no match for 'operator*' (operand type is 'VariantData ....'

我不知道如何解決此錯誤。 PS。 總體而言,該代碼運行良好-如果我注釋掉與解引用有關的這一部分,那么一切都會順利進行。

錯誤消息是不言自明的:您不能取消引用boost::variant ,它沒有這種語義。 您應該首先提取值(即指針),然后取消引用。

要提取依賴於運行時邏輯的值,只需調用get():

//method body
if(some_cond){ // if true, then it implies that var is of type myobj **
    do_something(*get<myobj **>(var));
}

但是請注意,如果運行時邏輯失敗(例如,由於錯誤),則get()將引發bad_get異常。

暫無
暫無

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

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