有没有办法从已经存在的元组创建新的元组?

bha*_*438 1 c++ c++17 c++20

我需要一种从另一个元组生成新元组的方法。

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;
}
Run Code Online (Sandbox Code Playgroud)

这只是我想做的一个最小的例子。有没有办法在 C++20 中做到这一点,也许使用std::tuple_cat

康桓瑋*_*康桓瑋 6

您可以使用std::apply以下方法来执行此操作:

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);
Run Code Online (Sandbox Code Playgroud)

演示

  • @Mgetz 做什么?我们不是连接两个元组,而是将一个元组更改为另一个元组。 (4认同)
  • 为什么不直接使用 [`std::tuple_cat`](https://en.cppreference.com/w/cpp/utility/tuple/tuple_cat)? (2认同)