Nesting error contexpr

The following code does not compile with g ++ / clang ++.

constexpr int bar(int v) { if (v > 0){ return v * 2; } return 2; } constexpr int foo(const int v) { constexpr auto x = bar(v); // error return v; } int main() { constexpr auto a = foo(1); constexpr auto b = bar(1); // ok } 

Error message: x must be initialized with a constant expression

But from the string (ok) you see that bar () is constexpr.

if I changed the body of foo () to

 constexpr int foo(const int v) { return bar(v); } 

He is well!

I do not understand this, why the first form is not possible. I used g ++ - 6.2.1, g ++ - 7.0.0 and clang ++ - 3.9.0

+5
source share
1 answer

The fix is

 constexpr int foo(const int v) { auto x = bar(v); return v; } 

The constexpr keyword means two very different things. The constexpr constant must be evaluated at compile time, while the constexpr function must be available for evaluation at compile time. There is nothing to stop you from calling foo at runtime. It means...

  • Argument v is not necessarily constexpr.
  • When bar is called with b, the answer may not be constexpr.
  • The result cannot be stored in the constexpr variable, since it cannot be constexpr.

If foo is called at compile time, then x is not saved, this is a temporary variable inside the compiler, so making it constexpr makes no sense.

Consistency x can only make sense if foo is evaluated at runtime, in which case it cannot be constexpr, in which cases an error occurs.

+5
source

Source: https://habr.com/ru/post/1260001/


All Articles