C++ 编译时静态数组的求和元素

C++ 编译时静态数组的求和元素,c++,arrays,c++11,metaprogramming,C++,Arrays,C++11,Metaprogramming,我想总结一下​​通过模板在编译时显示静态数组的元素: #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* ar

我想总结一下​​通过模板在编译时显示静态数组的元素:

#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;
}
#包括
模板
结构静态累积:
积分常数
{   };
模板
结构静态_累积:标准::积分_常数
{   };
constexpr int arr[9]={1,2,3,
4, 5, 6,
7, 8, 9};
int main()
{   

std::cout将模板参数更改为
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++11中的constexpr。