1

We have aggregate initialisation since C++11:

struct S {
    int count;
    double value;
};
S s{2, 3.0};

but in order for this work:

vector<S> v;
v.emplace_back(2, 3.0);

we need to manually write a constructor for no reason:

struct S {
    int count;
    double value;
    S(int count, double value): count(count), value(value) {}
};

We also need this constructor for optional(in_place, ...) and variant(in_place_type<>, ...) to work.

Is there a workaround for not writing this constructor manually?

It doesn't add any information just repeats what's already there, twice. Also the compiler is able to write it itself as it did it for the aggregate initialisation.

I was able to add new constructors to Egg's variant which allowed this but can we do something without modifying the container's source?

Edit: this question: Why doesn't emplace_back() use uniform initialization? is related but does not offer a workaround.

tamas.kenez
  • 7,301
  • 4
  • 24
  • 34

1 Answers1

0

You have at least one implicit constructor available.

std::vector<S> v;
v.emplace_back(S{2, 3.0});

(emplace_back and push_back are interchangeable in this context.)

bipll
  • 11,747
  • 1
  • 18
  • 32