Here the given program will explain how boost variant will helpful when there is a situation like, we need to return multiple types. There may be situations like we cannot use templates. In such cases boost variant will be the best solution.
Whenever you use boost::variant you should be very careful. If you are C++ beginner like me, definitely you may have a chance get an error message like this
"terminate called after throwing an instance of 'boost::bad_get' what(): boost::bad_get: failed value get using boost::get Aborted (core dumped)"
This is because you need to specifically get (boost::get) the value from boost::variant variable with it's type. If you try to boost::get by wrong type then you will get the above error message.
How to know about type of value inside a boost variant variable
#include <iostream> #include <string> #include <boost/variant.hpp> boost::variant<int,double,std::string> foo(int someValue) { if(0 == someValue) { return 1; } else if(someValue < 0) { return 2.5; } else { return "hello"; } } int main() { //In this case the return value is an integer boost::variant<int,double,std::string> value1 = foo(0); int integerValue = boost::get<int>(value1); //In this case the return value is a double boost::variant<int,double,std::string> value2 = foo(-1); double doubleValue = boost::get<double>(value2); //In this case the return value is an std::string boost::variant<int,double,std::string> value3 = foo(1); std::string stringValue = boost::get<std::string>(value3); return 0; }
Whenever you use boost::variant you should be very careful. If you are C++ beginner like me, definitely you may have a chance get an error message like this
"terminate called after throwing an instance of 'boost::bad_get' what(): boost::bad_get: failed value get using boost::get Aborted (core dumped)"
This is because you need to specifically get (boost::get) the value from boost::variant variable with it's type. If you try to boost::get by wrong type then you will get the above error message.
How to know about type of value inside a boost variant variable
boost::variant<int, double, std::string> someVariable; someVariable = "Hello World";"someVariable.which()" will give index of the type as declared in variable. In this case it will give index as 2.