C++11: I can go from multiple args to tuple, but can I go from tuple to multiple args?(C++11:我可以从多个 args 到 tuple,但是我可以从 tuple 到多个 args 吗?)
问题描述
可能的重复:
如何将元组扩展为可变参数模板函数争论?
“解包”调用匹配函数指针的元组
在 C++11 模板中,有没有办法使用元组作为(可能是模板)函数的单个参数?
In C++11 templates, is there a way to use a tuple as the individual args of a (possibly template) function?
示例:
假设我有这个功能:
Example:
Let's say I have this function:
void foo(int a, int b)
{
}
我有元组 auto bar = std::make_tuple(1, 2)
.
我可以使用它以模板方式调用 foo(1, 2)
吗?
Can I use that to call foo(1, 2)
in a templaty way?
我的意思不是简单的 foo(std::get<0>(bar), std::get<1>(bar))
因为我想在一个模板中做到这一点不知道参数的数量.
I don't mean simply foo(std::get<0>(bar), std::get<1>(bar))
since I want to do this in a template that doesn't know the number of args.
更完整的例子:
template<typename Func, typename... Args>
void caller(Func func, Args... args)
{
auto argtuple = std::make_tuple(args...);
do_stuff_with_tuple(argtuple);
func(insert_magic_here(argtuple)); // <-- this is the hard part
}
我应该注意,我不希望创建一个适用于一个参数的模板,另一个适用于两个参数等......
I should note that I'd prefer to not create one template that works for one arg, another that works for two, etc…
推荐答案
试试这个:
// implementation details, users never invoke these directly
namespace detail
{
template <typename F, typename Tuple, bool Done, int Total, int... N>
struct call_impl
{
static void call(F f, Tuple && t)
{
call_impl<F, Tuple, Total == 1 + sizeof...(N), Total, N..., sizeof...(N)>::call(f, std::forward<Tuple>(t));
}
};
template <typename F, typename Tuple, int Total, int... N>
struct call_impl<F, Tuple, true, Total, N...>
{
static void call(F f, Tuple && t)
{
f(std::get<N>(std::forward<Tuple>(t))...);
}
};
}
// user invokes this
template <typename F, typename Tuple>
void call(F f, Tuple && t)
{
typedef typename std::decay<Tuple>::type ttype;
detail::call_impl<F, Tuple, 0 == std::tuple_size<ttype>::value, std::tuple_size<ttype>::value>::call(f, std::forward<Tuple>(t));
}
示例:
#include <cstdio>
int main()
{
auto t = std::make_tuple("%d, %d, %d
", 1,2,3);
call(std::printf, t);
}
通过一些额外的魔法并使用 std::result_of
,您可能还可以使整个事物返回正确的返回值.
With some extra magic and using std::result_of
, you can probably also make the entire thing return the correct return value.
这篇关于C++11:我可以从多个 args 到 tuple,但是我可以从 tuple 到多个 args 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++11:我可以从多个 args 到 tuple,但是我可以从


基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30