【发布时间】:2017-05-24 15:26:25
【问题描述】:
考虑以下代码,使用 g++ 7.0.1 (-std=c++17) 编译:
#include <map>
#include <tuple>
int main()
{
// Create an alias for a tuple of three ints
using ThreeTuple=std::tuple<int,int,int>;
// Create an alias for a map of tuple to tuple (of three ints)
using MapThreeTupleToThreeTuple=std::map<ThreeTuple,ThreeTuple>;
MapThreeTupleToThreeTuple m;
// The following does NOT compile
m.emplace({1,2,3},{4,5,6});
// ..., and neither does this
m.emplace(std::piecewise_construct,{1,2,3},{4,5,6});
}
我原以为map::emplace() 的initializer_list 参数就足够了,并且会导致插入指定的元组键到元组值关联。显然,编译器不同意。
当然,显式创建一个元组(即ThreeTuple{1,2,3} 而不仅仅是{1,2,3})并将其传递给map::emplace() 可以解决问题,但是为什么不能将初始化列表直接传递给map::emplace()自动将它们转发给元组构造函数?
【问题讨论】:
-
初始化列表没有类型。
emplace依赖于类型推导。你不能为无类型的东西推断出类型。 -
您认为 C++17 在这个问题上发生了什么变化?
-
@Walter,我并不是要暗示我正在使用新的 C++17 功能,只是说我使用的是 C++17 兼容级别。