简体   繁体   English

映射值类型的decltype?

[英]decltype for map value type?

Is this legal in c++11: 在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 4.6.3中尝试了此方法,但没有成功。 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. 我想c ++ 11不能解决这个问题或使其变得更容易。

The code is correct C++. 该代码是正确的C ++。 Like Basile alluded to in a comment, this was a bug that was fixed for GCC 4.7. 就像Basile在评论中提到的那样,这是针对GCC 4.7修复的错误。

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. 这将有效地构造std::pair So no need for ugly things like decltype and such. 因此,无需使用诸如decltype类的丑陋的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM