Hello, are there any ways to restore type of packed into boost::any object? If now, can I store some association map for it? I need something like (pseudocode):
map<key, any> someMap;
someMap["Key"] = some own object;
getType("Key");
Hello, are there any ways to restore type of packed into boost::any object? If now, can I store some association map for it? I need something like (pseudocode):
map<key, any> someMap;
someMap["Key"] = some own object;
getType("Key");
Are you trying to get the type of the value, or just cast it back to what it was? If you just want to cast it, just use boost::any_cast
:
boost::any val = someMap["Key"];
RealType* r = boost::any_cast<RealType>(&val);
Not arbitrarily, you need to have some static type(s) you want to work with in C++.
So you can test for or cast to a specific type using any::type()
and any_cast()
, e.g.:
const boost::any& any = someMap["Key"].type();
if (int* i = boost::any_cast<int>(&any)) {
std::cout << *i << std::endl;
} else if (double* d = boost::any_cast<double>(&any)) {
// ...
But something like the following can not be done in general due to C++ being statically typed:
magically_restore_type(someMap["Key"]).someMethod();
Using something like boost::any
in C++ is almost always not a good idea, exactly because handling arbitrary types is no fun. If you only need to handle a known finite set of types, don't use boost::any
- there are better options like boost::variant
or polymorphic classes.
Let's say you did have such a function to extract the correctly-typed extraction from a boost::any. What would the return value of this function be? What would your code look like?
// Extracts v and returns the correct type... except we can't do that in C++. Let's just call it MagicalValue for now.
MagicalValue magic(const boost::any& v);
void perform_magic(const boost::any& v)
{
MagicalValue r = magic(v);
r.hello_world(); // Wait, what?
}
You can't do this type of trickery in statically-typed languages. What you can try is polymorphism instead of boost::any. This gives you a common interface you CAN use in C++.