C++::Boost::Variant::Apply_visitor( )














































C++::Boost::Variant::Apply_visitor( )



Description-

boost.variant provides function for type safe access i.e boost::apply_visitor().

It takes two parameters as input. As its first paramenter, boost::apply_visitor() expects an object of a class derived from boost::static_visitor.This class must overload  operator() for every type used by the  boost::variant variable it acts on. Consequently, the operator is overloaded three times in the code because variant variable supports the types  double, char, and std::string.

The second parameter passed to boost::apply_visitor() is a boost::variant  variable.

boost::apply_visitor() automatically calls the operator() for the first parameter that matches the type of the value currently stored in the second parameter. This means that the sample program uses different overloaded operators every time boost::apply_visitor() is invoked %u2013 first the one for double, followed by the one for char, and finally the one for std::string.

Advantages of using boost::apply_visitor( )-

The advantage of boost::apply_visitor() is not only that the correct operator is called automatically. In addition, boost::apply_visitor() ensures that overloaded operators have been provided for every type supported by boost::variant variables. If one of the three overloaded operators had not been defined, the code could not be compiled.

If overloaded operators are equivalent in functionality, the code can be simplified by using a template 


Code -

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

struct output : public boost::static_visitor<>
{
void operator()(double d) const { std::cout << d << '\n'; }
void operator()(char c) const { std::cout << c << '\n'; }
void operator()(std::string s) const { std::cout << s << '\n'; }
};

int main()
{

output o1;
boost::variant<
double, char, std::string> v;
v = 9.45
;
boost::apply_visitor(output o1, v);
v =
'V';
boost::apply_visitor(output o1, v);
v =
"Cppsecrets.com";
boost::apply_visitor(output o1, v);
}

Output

9.45
V
Cppsecrets.com

Comments