可能的重复:
如何将元组扩展为可变参数模板函数争论?
“解包”调用匹配函数指针的元组
在 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 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!