【发布时间】:2014-08-08 15:20:13
【问题描述】:
所以我遇到了将可变参数存储在元组中以便稍后使用这些调用函数的问题。我找到了Kerrek SB 的答案,它做得很好,但我不明白它到底做了什么。代码如下:
// 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));
}
基本上,困扰我的部分如下:
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));
}
};
我知道 N... 和 sizeof...(N) 存在某种 TMP 递归,这会在 Done 设置为 true 的部分特化中停止,这在验证条件 Total == 1 + sizeof...(N) 时会发生。
我不明白这个N... 是从哪里来的。我看不出它从哪里开始......
有人能解释一下这个实现是如何工作的吗? (如果这不是 SO 的主题)。
【问题讨论】:
标签: c++ templates tuples variadic-templates template-meta-programming