#include#include #include int main() { boost::variant v; v = 42; std::cout << v << '\n'; v = "hello"; std::cout << v << '\n'; }
#includeIn this example, a `boost::variant` is created that can hold either an `int` or a `std::string` value. A `MyVisitor` class is defined that implements two `operator()` methods that are used to print the stored value in the `boost::variant`. The `boost::apply_visitor` function is used to apply the visitor object to the `boost::variant`. The correct `MyVisitor::operator()` method is called based on the stored data type of the `boost::variant`. Conclusion: The examples of using `boost::variant` shows how to store different types of data in a single variable and how to access data from a `boost::variant` using `boost::apply_visitor`. The library used for these examples is `Boost`.#include #include class MyVisitor : public boost::static_visitor<> { public: void operator()(int value) const { std::cout << "int value: " << value << '\n'; } void operator()(const std::string& value) const { std::cout << "string value: " << value << '\n'; } }; int main() { boost::variant v; v = 42; boost::apply_visitor(MyVisitor(), v); v = "hello"; boost::apply_visitor(MyVisitor(), v); }