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

标签 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* 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/

相关文章:

c - 在公式中递增数组

c++ - 移动构造函数模板省略

VS2012 C++类特殊成员函数默认并删除

c++ - 卡在访问方法 C++

c++ - 如何在 OSX lion 上使用 clang 3.2 编译 C++11?

c++ - 尝试在项目中包含 boost::thead 时未定义对 "__gx_personality_sj0"和其他引用

iphone - 在 SQLite 中保存数组的最佳方法是什么?

c++ - 如何使用指向指针的指针存储 Polyomino 的对称性?

c++ - FindFirstFileW 通配符匹配

c++ - "no diagnostic required"的基本原理是什么?