Emplace directly in std :: map pairs

Why is this code not compiling?

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

Assuming we can edit the code std::map::emplace, can we change it to make the previous code valid?

+4
source share
1 answer

Not valid for the same reason that this is not true:

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

Because above is essentially what the card comes down to emplace.

To make it work, you can use the constructor that was introduced just for this purpose: piecewise_construct std::pair

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

This will have the desired effect so as not to cause unnecessary constructors (even if they are likely to be eliminated).


"" : map<K, V>, no. :

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 , , ). , , .

+8

All Articles