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

Is there a way to create a new tuple from an already exisiting tuple?

I need a way to generate a new tuple from another tuple.

std::string f1(int a)
{
    std::string b = "hello";
    return b;
}

float f2(std::string a)
{
    float b = 2.5f;
    return b;
}

int f3(float a)
{
    int b = 4;
    return b;
}

int main()
{
    auto t1 = std::make_tuple(1, "a", 1.5f);
    //New tuple ---> std::tuple<std::string, float, int>(f1(1), f2("a"), f3(1.5));
    return 0;
}

This is just a minimal example of what I want to do. Is there a way of doing this in C++20, maybe using std::tuple_cat?

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 :

You can use std::apply to do this:

template<class Tuple, class... Fns>
auto tuple_transform(const Tuple& t, Fns... fns) {
  return std::apply([&](const auto&... args) {
    return std::tuple(fns(args)...);
  }, t);
}

auto t1 = std::make_tuple(1, "a", 1.5f);
auto t2 = tuple_transform(t1, f1, f2, f3);

Demo

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