3

In C++, the constexpr specifier must be specified by the programmer on a constexpr function. The compiler is not allowed to infer the constexpr-ness of a function.

Yet, the standard allows a function to be marked as constexpr as long as there exists one set of argument values such that the function can be evaluated at compile time.

Consider this code:

#include <iostream>
#include <type_traits>

constexpr int constexpr_stuff() { return 1 + 2 * 3 + 4; }
int non_constexpr_stuff() {
    int tmp =0;
    std::cin >> tmp;
    return tmp;
}

int f() {
    return constexpr_stuff();
}

constexpr int g(int x) {
    if (x == 0) return constexpr_stuff();
    else return non_constexpr_stuff();
}

// constexpr int k1 = f(); // compile error
constexpr int k2 = g(0); // ok
// constexpr int k3 = g(1); // compile error

f is a non-constexpr function, so it is a compile error to assign its result to a constexpr variable. However, g is conditionally constexpr, and the compiler is clearly capable of inferring that g(0) is constexpr.

Is there any technical reason why the standard does not allow the compiler to infer the constexpr-ness of a function?

Bernard
  • 5,209
  • 1
  • 34
  • 64

0 Answers0