tags:

views:

64

answers:

3

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");
A: 

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);
lrm
I don't know that real type. In any map there are stored different data. I should restore each type.
Ockonal
You need to either (a) know what type you want to restore; (b) have a way of determining the type you want to restore; or, (c) guess which type you want to restore by trying each of the possibles. Do all of the possible types derive from a common base class?
lrm
A: 

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.

Georg Fritzsche
What about some another map with association? Like Key -> Type, Key -> Value.
Ockonal
@Ockonal: The problem remains the same, you have to explicitly handle the different types that might be stored - C++ has no *"runtime duck-typing"*. `any` already has the type information, you just need to explicitly act on it.
Georg Fritzsche
A: 

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++.

Clark Gaebel