简体   繁体   English

有关使用boost :: variant重新加载运算符的编译错误

[英]Compilation error about operator reloading using boost::variant

I'am trying to learn boost.variant. 我正在努力学习boost.variant。 However, the code which I copied from a book won't pass the compilation: 但是,我从书中复制的代码不会通过编译:

class var_print : public boost::static_visitor<void>    
{
public:
    template<typename T>    
    void operator()(T &i) {  
        i *= 2;   
        cout<<i<<endl;  
    }
};

Here is how I tried to use it. 这是我尝试使用它的方式。

    typedef boost::variant<int,double,string> var_t;
    var_t v(1); //v->int 
    boost::apply_visitor(var_print(),v);

The compiler generates the following error: 编译器生成以下错误:

ERROR:no match for 'operator*=' in 'i *= 2' 错误:'i * = 2'中的'operator * ='不匹配

That puzzles me,since template function will determine the type of parameter whenever it's called and int should defined the operator *=. 这让我很困惑,因为模板函数会在调用时确定参数的类型,而int应该定义运算符* =。

You need to have a separate operator() for std::string& since no operator *= is defined for std::string . 你需要为std::string&提供一个单独的operator() ,因为没有为std::string定义operator *=

In addition, your operator must be marked const since you are passing a temporar visitor instance to apply_visitor . 此外,由于您要将临时访问者实例传递给apply_visitor ,因此必须将您的运算符标记为const

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM