第十五章:元编程(二)

循环语句的编写方式

首先我们来看一个简单的例子:计算二进制中包含 1 的个数

template <int x>
constexpr  auto fun = (x % 2) + fun<x/2>;

template<>
constexpr auto fun<0> = 0;

在编译期我们通常会使用递归来实现循环。

此外,任何一种分支代码的编写方式都对应相应的循环代码编写方式。

接下来我们再来看一个例子:使用循环处理数组并获取数组中 id=0,2,4,6… 的元素

template <typename...> class Cont;
using Input = Cont<int, char, double, bool, void>;

template <typename Res, typename Rem>
struct Imp{
    using type = Res;
};

template <typename... Processed,typename T1, typename T2, typename... TRemain>
struct Imp<Cont<Processed...>, Cont<T1,T2,TRemain...>>
{
    using type1 = Cont<Processed..., T1>;
    using type = typename Imp<type1,Cont<TRemain...>>::type;
};

template <typename... Processed,typename T1>
struct Imp<Cont<Processed...>, Cont<T1>>
{
    using type = Cont<Processed..., T1>;
};

template <typename... Processed>
struct Imp<Cont<Processed...>, Cont<>>
{
    using type = Cont<Processed...>;
};

using Output = Imp<Cont<>,Input>::type;

最后,我们来看一个相对比较复杂的例子:获取数组中最后三个元素

template <typename...> class Cont;
using Input = Cont<int, char, double, bool, void>;

template <typename Res, typename Rem>
struct Imp
{
    using type = Res;
};

template <typename U1, typename U2, typename U3, typename T, typename... TRemain>
struct Imp<Cont<U1,U2,U3>, Cont<T,TRemain...>>
{
    using type1 = Cont<U2,U3,T>;
    using type = typename Imp<type1,Cont<TRemain...>>::type;
};

template <typename U1, typename U2, typename T, typename... TRemain>
struct Imp<Cont<U1,U2>, Cont<T,TRemain...>>
{
    using type1 = Cont<U1,U2,T>;
    using type = typename Imp<type1,Cont<TRemain...>>::type;
};

template <typename U1, typename T, typename... TRemain>
struct Imp<Cont<U1>, Cont<T,TRemain...>>
{
    using type1 = Cont<U1,T>;
    using type = typename Imp<type1,Cont<TRemain...>>::type;
};

template <typename T, typename... TRemain>
struct Imp<Cont<>, Cont<T,TRemain...>>
{
    using type1 = Cont<T>;
    using type = typename Imp<type1,Cont<TRemain...>>::type;
};


using Output = Imp<Cont<>,Input>::type;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值