Assume that you have a boost::any
object and a boost::variant
object.
I'm looking for a generic function convert
, that takes a template parameter T being a specialized boost::variant
e.g. boost::variant<int, std::string>
and magically converts the boost::any
to one of the available types of the given boost::variant
.
template<T>
T convert(const boost::any& any) {
// Some generic conversion code here or throw exception if conversion is not possible!
}
int main(int argc, char** args) {
typedef boost::variant<int, std::string> TVar;
boost::any any="Hello World";
TVar variant=convert<TVar>(any);
// variant contains "Hello World"
return 0;
}
I'm wondering if it is possible to write such a function or if it might be impossible for some reason?
Let's enclose all code in struct templated by variant type
You can easily write a function that for given type tries to convert boost::any to variant of this type
Now using boost::mpl you can iterate through all variant types to generate function for each variant's type
And now you just apply all created functions:
You can call
boost::any_cast
for each of the types withinboost::variant
and stop when the first cast succeeded:live example
In case none of the casts succeeded, an exception is thrown, see the following live example.