Semjon Mössinger
Semjon Mössinger

Reputation: 1890

How to modify boost::apply_visitor to return a value?

I am trying to use boost::variant and boost::apply_visitor. This already works except when I try to make the Vistor's functions to return a (boolean) value. I saw a lot of examples on SO doing this but I wasn't able to create a working sample. This is my code without return value:

#include <iostream>
#include <boost/variant.hpp>
#include <string>
#include <conio.h>


class CnVisitor : public boost::static_visitor<>
{
public:
    void operator()(double& valueFloat ) const
    {
        std::cout << (double)valueFloat;
    }

    void operator()(std::string& valueString ) const
    {
        std::cout << valueString.c_str ();
    }
};


int main()
{
    std::vector< boost::variant< double, std::string >> vec;

    vec.push_back((double)1.423423);
    vec.push_back((std::string)"some text");

    CnVisitor l_Visitor;

    for ( int i = 0; i < vec.size (); ++i )
    {
        boost::apply_visitor ( l_Visitor, vec[i] );
    }

    _getch ();
}

Upvotes: 4

Views: 6539

Answers (1)

Semjon M&#246;ssinger
Semjon M&#246;ssinger

Reputation: 1890

I found the solution myself by comparing with other examples. You must modify not only the functions (A) but also the declaration of Static_visitor (B)

  • (A) bool operator()(double& valueFloat ) const
  • (B) class CnVisitorReturn : public boost::static_visitor<bool>

Showing the modified sample:

#include <iostream>
#include <boost/variant.hpp>
#include <string>
#include <conio.h>

class CnVisitorReturn : public boost::static_visitor<bool>
{
public:
    bool operator()(double& valueFloat ) const
    {
        std::cout << (double)valueFloat;
        return true;
    }

    bool operator()(std::string& valueString ) const
    {
        std::cout << valueString.c_str ();
        return true;
    }
};


int main()
{
    std::vector< boost::variant< double, std::string >> vec;

    vec.push_back((double)1.423423);
    vec.push_back(static_cast<std::string>("some text"));

    CnVisitorReturn l_VisitorReturn;

    for ( int i = 0; i < vec.size (); ++i )
    {
        bool temp = boost::apply_visitor ( l_VisitorReturn, vec[i] );
    }

    _getch ();
}

Upvotes: 9

Related Questions