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 ();
}
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)
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 ();
}