使用 boost::variant 时运算符 * 不匹配
No match for operator * when using boost::variant
我定义自己的 variant
类型,如下所示:
typedef variant<myobj **, ... other types> VariantData;
我的一个 class 方法获取此数据类型作为参数并尝试执行如下操作:
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
异常。
我定义自己的 variant
类型,如下所示:
typedef variant<myobj **, ... other types> VariantData;
我的一个 class 方法获取此数据类型作为参数并尝试执行如下操作:
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
异常。