Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't get pair from map value

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading