0
struct Foo {
    Foo(int a, int b) : a_(a), b_(b) {}
    int a_;
    int b_;
};

int main() 
{
    vector<Foo> vec;
    vec.emplace_back(1, 2);
}

The above code compiles since emplace_back constructs the Foo object in place.

int main() 
{
    map<int, Foo> m;
    m.emplace(1, 2, 3);
}

The above code does not compile. Why does emplace not construct Foo in place using args 2 and 3 ? If Foo constructor has 1 arg, the above style works.

I am using gcc 4.9.2 which is not the latest. Does anyone think the above code would compile in later compilers ?

Praetorian
  • 106,671
  • 19
  • 240
  • 328

1 Answers1

3

The value_type of your map is std::pair<const int, Foo>. pair does not have a constructor taking three int arguments.

You can do

m.emplace(1, Foo(2, 3));

Or if you really don't want to call a move constructor of Foo,

m.emplace(std::piecewise_construct,
          std::make_tuple(1),
          std::make_tuple(2, 3));
aschepler
  • 70,891
  • 9
  • 107
  • 161