如何累积模板参数包?

时间:2018-09-16 09:22:59

标签: c++ templates variadic-templates

假设我要启用此功能:

template <int a,int b> struct add_base{ static const int value = a+b;};
template<int...a> using add = accumulate<add_base,0,a...>;

template <int a,int b> struct mult_base{ static const int value = a*b;};
template<int...a> using mult = accumulate<mult_base,1,a...>;

template <int a,int b> struct sqsum_base{ static const int value = a+b*b;};
template<int...a> using sqsum = accumulate<sqsum_base,0,a...>;

static_assert( add<1,2,3>::value == 6 );
static_assert( mult<2,2,2>::value == 8 );
static_assert( sqsum<1,2,3>::value == 14 );

我的accumulate如下:

template <template <int,int> class G,
          int first, int second,
          int...more> 
struct accumulate {
    static const int value = accumulate<G,G<first,second>::value,more...>::value;
};
template <template <int,int> class G,
          int first, int second> 
struct accumulate<G,first,second> {
    static const int value = G<first,second>::value;
};

现在,我想知道是否可以通过扩展内联代码来简化accumulate,例如:

template <template <int,int> class G,
          int first,int second,
          int...more> 
struct accumulate {
        static const int value = G< G<first,second>::value , more...>::value;
};

这是错误的,将导致

  
    

错误:模板参数数量错误(3个应为2)

  

是否可以解包参数以在一行中递归实例化G?如果不是,如何写accumulate而不必写专门的文字?

1 个答案:

答案 0 :(得分:4)

如果您的编译器支持C ++ 17,那么您可能要利用折叠表达式:

template<int ... x_item> struct
accumulate
{
    static inline constexpr int const s_value{(0 + ... + x_item)};
};

static_assert(6 == accumulate<1, 2, 3>::s_value);

online compiler

参数化操作示例:

template<typename x_Op, int ... x_items> struct
accumulate
{
    static inline constexpr int const s_value{(x_Op{0} + ... + x_Op{x_items}).value};
};

struct
sq_sum
{
    int value;
};

inline constexpr sq_sum
operator +(sq_sum left, sq_sum right)
{
    return sq_sum{left.value + right.value * right.value};
}

static_assert(14 == accumulate<sq_sum, 1, 2, 3>::s_value);

online compiler