编译时静态数组的元素总和

Sum elements of static array in compile-time

本文关键字:元素 数组 静态 编译      更新时间:2023-10-16

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

#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;
}

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

错误:无法将模板参数"arr"转换为"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 *'