On Mon, 27 Apr 2020 at 04:54, Laleh Aghababaie via Gcc <[email protected]> wrote:
>
> Hi all,
N.B. this is the wrong mailing list for such a question, you should
have used the gcc-help list instead.
> I have a question about the constexpr variable specifications and how the
> compiler handles them. The constexpr specifier declares that it is possible
> to evaluate the value of the function or variable “at compile time”. If we
> look at the bellow simplified example:
>
> int func(){
> int sum = 0;
> for (int i = 0; i < 3; i++){
> constexpr int j = i;
> sum +=j;
> }
> return sum;
> }
>
> The compiler will throw an error as:
>
> “The value of ‘i' is not usable in a constant expression.”
> However the value of ‘i’ is known during the compile time, and if I unroll
> this computation myself it works perfect, so why the compiler is not able to
> do that?
The compiler *could* do it, but the rules of the C++ standard do not
allow a constexpr variable to have an initializer that is nto a
constant expression. The loop variable i is not a constant expression,
obviously, because its value changes.
> The main reason I am asking this is because I want to call a constexpr
> function for a few iteration which is known at compile time (instead of that
> “sum” in the for loop) , but using the iteration number in the call is
> prohibited, even though the number of iterations and iteration number is
> known during the compile time to do the sum. When unrolling it by hand works,
> why the compiler refuses to handle this situation?
Because it's not valid C++.
If you want to process a sequence of integer constants there are
various metaprogramming techniques you can use e.g create
std::integer_sequence<int, 0, 1, 2, 3> and pass it to a function
template that accepts an int... pack, and expands it in a fold
expression.