Suppose I have a struct, used later in a vector. I want to added an element to the vector using emplace_back without creating temporaries. I expected I would be able to use std::forward_as_tuple to pass two values as parameters for Foo. However, it fails to compile.
What’s the right way to do this?
#include <utility>
#include <vector>
struct Foo {
int a;
float b;
Foo(int a, float b) : a(a), b(b) {}
};
std::vector<tuple<int, int, Foo>> vec;
vec.emplace_back(0, 1, std::forward_as_tuple(1, 2.0f));
Of course, I could do this:
vec.emplace_back(0, 1, Foo(1, 2.0f));
But this creates a temporary Foo which defeats the purpose of using emplace_back in the first place.
>Solution :
A way that you can do this is to add a tuple constructor to Foo.
struct Foo {
int a;
float b;
Foo(int a, float b) : a(a), b(b) {}
Foo(std::tuple<int, float> tup) : a(get<0>(tup)), b(get<1>(tup)) {}
};
If you were using std::pair, you could use the std::piecewise_construct_t constructor, however there isn’t a variadic version of that.
std::vector<std::pair<int, Foo>> vec;
vec.emplace_back(std::piecewise_construct, std::tuple(1), std::forward_as_tuple(1, 2.0f));