Search code examples
c++constexprc++20consteval

How come constexpr functions can not consume consteval functions while you can create constexpr objects from consteval functions?


You can have constexpr objects fron consteval but you can not consume consteval within constexpr.

Why?

I thought consteval should have been some kind of "narrow" constexpr.

Please help me make a sense out of this design.

constexpr int constexpr_sqr(int n) { return n*n; }
consteval int consteval_sqr(int n) { return n*n; }
constexpr int constexpr_sqr2(int n) { 
  // not allowed
  // return consteval_sqr(n);
   
  // not allowed
  // constexpr imm = consteval_sqr(n);
  // return imm;

  return constexpr_sqr(n);
}
int main() {
  // while can do this
  constexpr auto imm = consteval_sqr(999);
}

[LIVE]


Solution

  • It's the argument. constexpr function aren't required to be constant evaluated. This means that n is not usable in a constant expression.

    I thought consteval should have been some kind of "narrow" constexpr.

    No, those are just functions that have to be constant evaluated. This means that their arguments must always be usable in a constant expressions.

    You can call a constexpr function with arguments that are not usable in a constant expression, and so long as you aren't in a context that requires a constant expression, it's still well-formed.