Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I have a temporary variable in a constexpr function?

Tags:

c++

constexpr

This is a simplified version what I would like to do.

constexpr float f(float a, float b){
    constexpr float temp = a+b;
    return temp*temp*temp;
}

In my version, a+b is something much more complicated, so I don't want to cut and paste it three times. Using 3*(a+b) is also not a working solution for the real function. I'm trying to keep the question related to syntax, and not algebra. I can get it to work by moving a+b to it's own constexpr function, but I'd prefer to not pollute the namespace with otherwise useless functions.

like image 783
John K Avatar asked Aug 11 '12 20:08

John K


1 Answers

As you've discovered, you can't declare variables, even constexpr ones, inside the body of a constexpr function.

It's still possible to factor out a common expression, by passing it in as an argument to a second constexpr function. For the example you've given here:

constexpr float pow3(float c) {
    return c*c*c;
}

constexpr float f(float a, float b) {
    return pow3(a+b);
}
like image 168
Veloso Avatar answered Nov 15 '22 00:11

Veloso