C++14 make_index_sequence的实现原理(简单明了)

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<>;
}

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值