Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using emplace_back on an std::vector of a tuple

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading