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

Time:09-09

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?

CodePudding user response:

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

  • Related