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

前端 未结 13 1253
旧时难觅i
旧时难觅i 2020-11-22 07:49

Consider the case of a templated function with variadic template arguments:

template Tret func(const T&... t);
         


        
13条回答
  •  暖寄归人
    2020-11-22 08:20

    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 
    
    template  void my_func(T &&t, U &&u) {}
    
    int main(int argc, char *argv[argc]) {
    
      std::tuple 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/.

提交回复
热议问题