我试图通过模板在编译时对静态数组的元素求和:
#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/