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 -
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
Name | Views | Likes |
---|---|---|
C++ boost::Variant | 1851 | 1 |
C++ BOOST::ALGORITHM::IS_DIGIT( ) | 526 | 0 |
C++ BOOST ::STRING ALGO::TO_UPPER_COPY( ) | 502 | 1 |
C++::boost::variant::static_visitor | 1690 | 1 |
C++::Boost::Variant::get( ) | 2412 | 1 |
C++ PROGRAM TO FIND MAX SUBTREE SUM IN A TREE | 404 | 1 |
C++ BOOST::ALGORITHM::STRING COMPARE | 1604 | 1 |
C++::Boost::Variant::Apply_visitor( ) | 2267 | 1 |
C++ BOOST ::STRING ALGO::ERASE( ) | 780 | 1 |
C++ BOOST::ALGORITHM::REPLACE | 1221 | 0 |
C++ BOOST::ALGORITHM::FIND FUNCTION | 819 | 1 |
C++ Boost::variant::variant | 390 | 2 |
GSD | 331 | 7 |
C++ BOOST::ALGORITHM::TRIM | 1106 | 1 |
Comments