【问题标题】:Sum elements of static array in compile-time在编译时对静态数组的元素求和
【发布时间】:2013-09-23 19:09:43
【问题描述】:

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

#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.

如何避免?

【问题讨论】:

  • 您可能只想看看 constexpr 与 C++11。

标签: c++ arrays c++11 metaprogramming


【解决方案1】:

将您的模板参数更改为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 *'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    相关资源
    最近更新 更多