gpt4 book ai didi

c++ - 在编译时对静态数组的元素求和

转载 作者:搜寻专家 更新时间:2023-10-31 01:47:42 25 4
gpt4 key购买 nike

我正在尝试通过模板在编译时对静态数组的元素求和:

#include <type_traits>

template<size_t idx, int* arr>
struct static_accumulate :
std::integral_constant<size_t, arr[idx] + static_accumulate<idx - 1, arr>::value>
{ };

template<int* arr>
struct static_accumulate<0, arr> : std::integral_constant<size_t, arr[0]>
{ };

constexpr int arr[9] = {1, 2, 3,
4, 5, 6,
7, 8, 9};

int main()
{
std::cout<<static_accumulate<8, arr>::value;
}

但是我得到了这个编译错误:

error: could not convert template argument ‘arr’ to ‘int*’

编译器 - gcc 4.7。

如何避免?

最佳答案

将模板参数更改为 int const * arr

Clang 的错误消息在这里实际上比 gcc 的更有帮助:

sum.cc:19:37: error: non-type template argument of type 
'int const[9]' cannot be converted to
a value of type 'int *'

关于c++ - 在编译时对静态数组的元素求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18882152/

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