Constexpr with intact non-constexpr arguments: who is right, clang or gcc?

I have 4 test cases, and I believe that they are all valid:

constexpr int f(int const& /*unused*/){ return 1; } void g(int const& p){ constexpr int a = f(p); // clang error, gcc valid int v = 0; constexpr int b = f(v); // clang valid, gcc valid int const& r = v; constexpr int c = f(r); // clang error, gcc error int n = p; constexpr int d = f(n); // clang valid, gcc valid } int main(){ int p = 0; g(p); } 

Clang and GCC differ only in the first test case.

I tested with clang 4 and 5 (20170319) and with GCC 7.0.1 (20170221).

If I am right, it will greatly simplify the use of boost :: hana in static_assert's.

+4
source share
1 answer

[expr.const] / 2 :

The expression e is an expression of a constant constant; estimate e , following the rules of an abstract machine, evaluate one of the following expressions:

  • [...]
  • id-expression that refers to a variable or data element of a reference type if the link has no previous initialization and either

    • it is initialized with a constant expression or

    • his lifetime began with an estimate of e ;

  • [...]

No condition is satisfied for p or r . Therefore, neither f(p) nor f(r) is a key constant expression, and therefore, none of them can be used to initialize the constexpr variable. Klang is right.

+3
source

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


All Articles