There is no issue with applying const to your TOTAL variable.
'const', in this context, just means 'read-only'. It's just a safety measure to communicate that you never intend to change the value of that variable.
What you can't do, however, is then use the result of TOTAL to initialize, say, the size of an array, or an enum, or a template argument, because those indeed do need to be compile-time constants. Is this what you are actually trying to do?
You could write your own C++20 equivalent with consteval:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
#include <iostream>
#include <numeric>
template <int N>
class Foo { };
namespace util {
template <typename Iter, typename T>
consteval T accumulate(Iter begin, Iter end, T init)
{
T sum = init;
for (Iter it = begin; it < end; it++)
{
sum += *it;
}
return sum;
}
}
int main()
{
constexpr int N = 2;
constexpr int MY_ARR[N]{3,4};
constexpr int TOTAL = util::accumulate(MY_ARR, MY_ARR + N, 0);
Foo<TOTAL> foo; // example: Use in template argument
std::cout << TOTAL << '\n';
}
| |
'consteval' truly forces compile-time compilation, while constexpr does not.
(But a consteval function can only work with constexpr or stronger values.)