Can't get pair from map value

Advertisements

I have this structure

static map<TypeA, pair<reference_wrapper<TypeB>, TypeC>> my_map;

Later, I access it like this:

pair<reference_wrapper<TypeB>, TypeC> instance = my_map[type_a_instance];

This error triggers:

no matching function for call to ‘std::pair<std::reference_wrapper< TypeB>, TypeC>::pair()’

>Solution :

map::operator[] must default construct the pair in the map if no mapping for the key exists. That’s not possible for the types in your map because of the reference_wrapper. Use find instead.

pair<reference_wrapper<TypeB>, TypeC> instance = 
    my_map.find(type_a_instance)->second;

Or use at as suggested by @Steve Lorimer

pair<reference_wrapper<TypeB>, TypeC> instance = 
   my_map.at(type_a_instance);

Of course both versions assume that the key can be found. The find version gives you undefined behaviour if the key is not found, the second gives a std::out_of_range exception.

Leave a Reply Cancel reply