C++11 emplace_back on vector<struct>?
You need to explicitly define a ctor for the class:
#include <string>
#include <vector>
using namespace std;
struct T
{
int a;
double b;
string c;
T(int a, double b, string &&c)
: a(a)
, b(b)
, c(std::move(c))
{}
};
vector<T> V;
int main()
{
V.emplace_back(42, 3.14, "foo");
}
The point of using emplace_back
is to avoid creating a temporary object, which is then copied (or moved) to the destination. While it is also possible to create a temporary object, then pass that to emplace_back
, it defeats (at least most of) the purpose. What you want to do is pass individual arguments, then let emplace_back
invoke the ctor with those arguments to create the object in place.
Of course, this is not an answer, but it shows an interesting feature of tuples:
#include <string>
#include <tuple>
#include <vector>
using namespace std;
using T = tuple <
int,
double,
string
>;
vector<T> V;
int main()
{
V.emplace_back(42, 3.14, "foo");
}
For anyone from the future, this behavior will be changed in C++20.
In other words, even though implementation internally will still call T(arg0, arg1, ...)
it will be considered as regular T{arg0, arg1, ...}
that you would expect.