我定义自己的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异常。

关于c++ - 操作符不匹配*使用boost::variant时,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31775508/

10-11 22:55
查看更多