Search code examples
c++pointersboostreferenceboost-any

casting pointers


I'm using ptr_map for storing different types of pointers.

boost::ptr_map<string, any> someMap;

I store there some templated class objects:

someMap.insert("1", new SomeClass<int>());
someMap.insert("2", new SomeClass<float>());

Now I want to get values from map. Here is a sample with references:

template<typename T>
T &get(const string &someKey)
{
    try
    {
        return any_cast<EventType&>(mSignalAssociation.at(signalName));
    } catch(bad_any_cast &e)
    {
        // Logging here
    }
}

get< SomeClass<int> >("1"); // This works

But I don't like references, because I can't return, for example, NULL if the casting is bad or the object doesn't exist.

How can I get pointer from this map?

T *get(const string &someKey)
{
   return any_cast<EventType*>(mSignalAssociation.at(signalName));
}

This builds but fails at casting, why?


Solution

  • how about this:

    T *get(const string &someKey)
    {
       return &any_cast<EventType&>(mSignalAssociation.at(signalName));
    }
    

    (Just a guess)