可变模板值作为结构的模板参数

variadic template value as template argument for struct

本文关键字:结构 参数      更新时间:2023-10-16

我试着做这样的事情:

template <int v1, template <typename... Args> Args... vx> struct Sum {
   const static int RESULT = v1 + Sum<vx...>::RESULT;
};
template <int v> struct Sum {
   const static int RESULT = v;
}

像这样使用:

int a = Sum<1, 2>::RESULT;
int b = Sum<1, 2, 3, 4, 5>::RESULT;

很明显,这里出了问题,我正在努力解决可变模板作为结构/类定义中的值的概念。有可能做这样的事吗?怎样

谢谢。。。

其中一个问题是,两个模板声明都没有专门针对另一个。这些声明中的代码不同,因此代码格式不正确。

此外,您实际上并没有在这里使用模板作为模板参数,代码也不需要它,正如您在这里看到的:

// main template
template <int v1, int... vx> struct Sum {
    const static int RESULT = v1 + Sum<vx...>::RESULT;
};
// specialization to make recursion terminate
// the list of matched template parameters is listed
// after the name of the struct in angle brackets
template <int v> struct Sum<v> {
    const static int RESULT = v;
};
static_assert(Sum<1, 2, 3, 4, 5>::RESULT == 15, "");
int main() {}