Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading