anio
anio

Reputation: 9161

decltype for map value type?

Is this legal in c++11:

std::unordered_map<X, Y> xy_map;
X my_x;
Y my_y;
xy_map.insert(decltype(xy_map)::value_type(my_x, my_y));

I tried this in gcc 4.6.3 and it did not work. GCC complains:

expected primary-expression before 'decltype'

I was hoping not to do:

typedef std::unordered_map<X, Y> MyMap;
xy_map.insert(MyMap::value_type(my_x, my_y));

I guess c++11 doesn't solve that or make it any easier.

Upvotes: 1

Views: 2449

Answers (2)

R. Martinho Fernandes
R. Martinho Fernandes

Reputation: 234424

The code is correct C++. Like Basile alluded to in a comment, this was a bug that was fixed for GCC 4.7.

Upvotes: 4

Nicol Bolas
Nicol Bolas

Reputation: 473352

This doesn't answer your question, but it does have the virtue of likely working on your compiler:

xy_map.emplace(my_x, my_y);

That will construct the value type from the given arguments. The first argument constructs the key, and the others are used for the value. This will effectively construct the std::pair in place. So no need for ugly things like decltype and such.

Upvotes: 2

Related Questions