Tho*_*mas 33 c++ templates variadic-templates c++11
在C++ 11模板中,有没有办法将元组用作(可能是模板)函数的各个args?
示例:
假设我有此功能:
void foo(int a, int b)
{
}
Run Code Online (Sandbox Code Playgroud)
我有元组auto bar = std::make_tuple(1, 2)
.
我可以用它以foo(1, 2)
一种模板的方式打电话吗?
我的意思并不简单,foo(std::get<0>(bar), std::get<1>(bar))
因为我想在一个不知道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
}
Run Code Online (Sandbox Code Playgroud)
我应该注意,我宁愿不创建一个适用于一个arg的模板,另一个适用于两个arg的模板等等...
Ker*_* SB 59
尝试这样的事情:
// 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));
}
Run Code Online (Sandbox Code Playgroud)
例:
#include <cstdio>
int main()
{
auto t = std::make_tuple("%d, %d, %d\n", 1,2,3);
call(std::printf, t);
}
Run Code Online (Sandbox Code Playgroud)
通过一些额外的魔法和使用std::result_of
,您可能还可以使整个事物返回正确的返回值.
归档时间: |
|
查看次数: |
23211 次 |
最近记录: |