"C2593: operator = is ambiguous" when filling in std :: map

I have std::map I'm trying to initialize using an initialization list. I do this in two places, in two different ways. The first one works, and the other causes the error indicated in the header.

Here's the one that works:

 void foo() { static std::map<std::string, std::string> fooMap = { { "First", "ABC" }, { "Second", "DEF" } }; } 

While this is not:

 class Bar { public: Bar(); private: std::map<std::string, std::string> barMap; }; Bar::Bar() { barMap = { // <-- this is the error line { "First", "ABC" }, { "Second", "DEF" } }; } 

Why am I getting an error when trying to initialize a class member, and does the static map work? At the moment, I can fill the element by first creating a local variable, and then replacing it with the following element:

 Bar::Bar() { std::map<std::string, std::string> tmpMap = { { "First", "ABC" }, { "Second", "DEF" } }; barMap.swap(tmpMap); } 

However, this seems rather contradictory compared to just filling the element directly.


EDIT: Here is the compiler output.

+7
c ++ c ++ 11
source share
1 answer

This is a mistake in your compiler overload resolution mechanism — or its standard library implementation. Overload resolution is clearly stated in [over.ics.rank] / 3, which

- The L1 initialization list sequence is a better conversion sequence than the L2 list initialization sequence if L1 converted to std::initializer_list<X> for some X and L2 not.

Here X is std::pair<std::string, std::string> . L1 converts your list to parameter

 map& operator=( std::initializer_list<value_type> ilist ); 

So far, L2 converts the list into one of the parameters of the following functions:

 map& operator=( map&& other ); map& operator=( const map& other ); 

This is clearly not initializer_list s.


You can try using
 barMap = decltype(barMap){ { "First", "ABC" }, { "Second", "DEF" } }; 

Which redirection operator should choose ( Demo with VC ++ ). Temporary should also be optimized according to copy.

+11
source share

All Articles