Can't get pair from map value

78 Views Asked by At

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()'

1

There are 1 best solutions below

2
john On BEST ANSWER

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 at version gives a std::out_of_range exception.