且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将元组扩展为可变参数模板函数的参数?

更新时间:2023-11-11 16:51:16

在 C++17 中你可以这样做:

In C++17 you can do this:

std::apply(the_function, the_tuple);

这已经适用于 Clang++ 3.9,使用 std::experimental::apply.

This already works in Clang++ 3.9, using std::experimental::apply.

回应评论说如果 the_function 被模板化,这将不起作用,以下是一种解决方法:

Responding to the comment saying that this won't work if the_function is templated, the following is a work-around:

#include <tuple>

template <typename T, typename U> void my_func(T &&t, U &&u) {}

int main(int argc, char *argv[argc]) {

  std::tuple<int, float> my_tuple;

  std::apply([](auto &&... args) { my_func(args...); }, my_tuple);

  return 0;
}

此变通方法是对将重载集和函数模板传递到预期函数的一般问题的简化解决方案.通用解决方案(处理完美转发、constexpr-ness 和 noexcept-ness 的解决方案)在此处提供:https://blog.tartanllama.xyz/passing-overload-sets/.

This work around is a simplified solution to the general problem of passing overload sets and function template where a function would be expected. The general solution (one that is taking care of perfect-forwarding, constexpr-ness, and noexcept-ness) is presented here: https://blog.tartanllama.xyz/passing-overload-sets/.