I'm trying to get the sum of a const int
array as a constexpr
so that I can use sum as the size of another array
constexpr int arr[] = {1, 2, 3};
constexpr int sum1 = std::accumulate(arr, arr + 3, 0); // not OK
int arr1[sum1];
The above does not compile as std::accumulate()
does not return a constexpr
. I end up have a workaround like this
template <size_t N>
constexpr int sum(int const a[])
{
return a[N-1] + sum<N - 1>(a);
}
template <>
constexpr int sum<0>(int const a[])
{
return 0;
}
constexpr int arr[] = {1, 2, 3};
constexpr int sum1 = sum<3>(arr);
int arr1[sum1];
Is there any simpler solution?