本文介绍了如何将元组扩展为可变参数模板函数的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑带有可变参数模板参数的模板函数的情况:

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

template<typename Tret, typename... T> Tret func(const T&... t);

现在,我有一个元组 t 值.如何使用元组值作为参数调用 func() ?我已经阅读了 bind() 函数对象,带有 call() 函数,还有 apply() 函数在不同的一些现在- 过时的文件.GNU GCC 4.4 实现似乎在 bind() 类中有一个 call() 函数,但关于该主题的文档很少.

Now, I have a tuple t of values. How do I call func() using the tuple values as arguments?I've read about the bind() function object, with call() function, and also the apply() function in different some now-obsolete documents. The GNU GCC 4.4 implementation seems to have a call() function in the bind() class, but there is very little documentation on the subject.

有些人建议使用手写递归技巧,但可变参数模板参数的真正价值在于能够在上述情况下使用它们.

Some people suggest hand-written recursive hacks, but the true value of variadic template arguments is to be able to use them in cases like above.

有没有人有解决方案,或暗示在哪里阅读?

Does anyone have a solution to is, or hint on where to read about it?

推荐答案

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

这篇关于如何将元组扩展为可变参数模板函数的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 18:37