How do I expand a tuple into variadic template function’s arguments?

In C++17 you can do this:

std::apply(the_function, the_tuple);

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

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;
}

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/.

Leave a Comment