循环语句的编写方式
首先我们来看一个简单的例子:计算二进制中包含 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;