直接在std :: pair中映射

问题描述 投票:4回答:1

为什么这段代码不能编译?

std::map<int,std::pair<int,int>> m;
m.emplace(1,1,1);

假设我们可以编辑std::map::emplace的代码,是否可以更改它以使以前的代码有效?

c++ dictionary c++14 std-pair emplace
1个回答
8
投票

它无效的原因完全相同:

std::pair<const int, std::pair<int, int>> p{1, 1, 1};

因为上面是地图的emplace归结为什么。

为了使它工作,你可以使用piecewise_construct constructor of std::pair,它是为了这个目的而引入的:

m.emplace(
  std::piecewise_construct,
  std::forward_as_tuple(1),
  std::forward_as_tuple(1, 1)
);

这将具有不调用任何不必要的构造函数的期望效果(即使它们可能被省略)。


回答关于使“直接”语法有效的假设问题:在任意map<K, V>的一般情况下,没有。想象一下:

struct Proof {
  Proof(int);
  Proof(int, int);
};

std::map<Proof, Proof> m;
m.emplace(1, 1, 1);  // Now what?

你当然可以让它适用于有限的map<T, std::pair<T, T>>案例。在大量的高级模板技巧的帮助下(或者考虑SFINAE左,右和中心,然后是一些),它可能对于一些更普遍的东西也是可行的。这是否值得,取决于您的具体情况。

© www.soinside.com 2019 - 2024. All rights reserved.