如何累积模板参数包?

问题描述 投票:2回答:1

假设我想要写这个:

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而不必编写专业化?

c++ templates variadic-templates
1个回答
4
投票

如果你的编译器支持C ++ 17那么你可能想要使用fold表达式:

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

© www.soinside.com 2019 - 2024. All rights reserved.