Search code examples
c++functorunordered-map

construct an unordered_map with value being a pair of string and object type


consider the following code:

namespace fruit {
    struct apple{
        ...
    };
}

namespace language{
    struct english{
        ...
    };
}

I want to do something like:

std::unordered_map<std::string, ? > mymap = { 
    {"paul", {"like", fruit::apple} },
    {"jonas", {"like", language::english} }
};

the key of my map is a string and the value should be such a pair <string, ? >.
What type should I give as value for my map? I think things like union or functor can be used to solve the problem, but how? thanks in advance.


Solution

  • So I found a solution using std::type_index.

    typedef std::pair<std::string, std::type_index> myPair;
    
    std::unordered_map<std::string, myPair> myMap =
    {
        {"paul", {"likes", std::type_index(typeid(fruit::apple))} },
        {"jonas",  {"likes", std::type_index(typeid(language::english))} }
    };
    

    thanks guys for your valuable suggestions.