c++boostboost-variantapply-visitor

why the below boost variant visitor code doesnt work


I have a struct A:

struct A
{
    //some implementation
}

My boost variants are:

boost::variant<double, A> v1 = 1.0;
boost::variant<double, A> v2 = 2.0;

My visitor functor is defined as:

class SomeWork:
    public boost::static_visitor<int>
{
public:
    
    int operator()(const A& data1, const A& data2) const
    {
        //some work
        return 1;
    }

    int operator()(const double& data1, const double& data2) const
    {
        //some work
        return 2;
    }

};
int main()
{
    boost::variant<double, A> v1 = 1.0;
    boost::variant<double, A> v2 = 2.0;

    boost::apply_visitor(SomeWork(), v1 ,v2);
    return 0;
};

When I do above I get an error saying:

error C2664: 'int SomeWork::operator ()(const A&, const A&) const': cannot convert argument 2 from 'T' to 'const double &'

Not sure why this happening.

boost version I am using is 107200

Thanks in advance.


Solution

  • boost::apply_visitor needs to consider every possible combination of types that your variant instances hold. This means SomeWork is missing the following combinations:

        int operator()(const A& data1, const double& data2) const
        {
            //some work
            return 3;
        }
    
        int operator()(const double& data1, const A& data2) const
        {
            //some work
            return 4;
        }
    

    When adding those, I'm able to compile your code.