Question

I'am trying to learn 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'

That puzzles me,since template function will determine the type of parameter whenever it's called and int should defined the operator *=.

Was it helpful?

Solution

You need to have a separate operator() for std::string& since no operator *= is defined for std::string.

In addition, your operator must be marked const since you are passing a temporar visitor instance to apply_visitor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top