gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:41:15 25 4
gpt4 key购买 nike

我试着做这样的事情:

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() {}

关于c++ - 可变参数模板值作为结构的模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31215993/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com