std::make_inedex_sequence<N>的作用是产生一个0,1,2,3,....,N-1的数列。我在STL源码中没有找到实现,所以参考网上的资料,尝试着给出一份自己理解的实现。
template<size_t... Args>
struct index_sequence{};
template<size_t N, size_t... M>
struct make_index_sequence : public make_index_sequence<N-1, N-1, M...>
{
};
template<size_t... M>
struct make_index_sequence<0, M...>: public index_sequence<M...>
{
};
这种写法的核心是M...起始为空,用头插法由N-1递归地扩展出0,1,2,..., N-1序列。以make_index_sequence<3>为例,递归扩展过程如图所示:
?网上我还看到另一种方法,采用尾插法:
template<size_t ... Args>
struct index_sequence{};
template<typename T, size_t newValue>
struct AppendNewValue;
template<size_t... Args, size_t newValue>
struct AppendNewValue<index_sequence<Args...>, newValue>{
using type = index_sequence<Args..., newValue>;
}
template<size_t N>
struct make_index_sequence
{
using type = typename AppendNewValue<typename make_index_sequence<N-1>::type, N-1>::type;
}
template<>
struct make_index_sequence<0>
{
using type = index_sequence<>;
}
|