Sum elements of static array in compile-time
I'm trying to sum ​​the elements of a static array in
compile-time via templates:
#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, 0>
{ };
constexpr int arr[9] = {1, 2, 3,
4, 5, 6,
7, 8, 9};
int main()
{
std::cout<<static_accumulate<8, arr>::value;
}
but I got this compile-error:
error: could not convert template argument 'arr' to 'int*'
compiler - gcc 4.7.
How I can avoid it?
No comments:
Post a Comment