Calling the constexpr method via a link is the result of a constant expression?

Following code

#include <array> void foo(const std::array<int, 42> &a) { constexpr size_t S = a.size(); } int main() {} 

compiles in GCC but does not compile in clang with the following error message

 main.cpp:5:28: error: constexpr variable 'S' must be initialized by a constant expression constexpr size_t S = a.size(); ^~~~~~~~ 

Meanwhile, many reports of constexpr issues on SO seem to imply that clang often has better (more pedantic?) Support for constexpr . So, which compiler would be right in this case?

Please note that both compilers gladly accept the code after replacing the reference parameter with the pass-by-value parameter.

+7
c ++ gcc language-lawyer clang constexpr
source share
1 answer

[expr.const] / 2 :

conditional expression e is an expression of a constant constant if the estimate e , following the rules of the abstract machine ([intro.execution]), evaluates one of the following expressions:

  • [...]
  • id expression that refers to a variable or data item of a reference type if the link does not have a previous initialization and either

    • it is initialized with a constant expression or
    • his life began with an estimate of e ;
  • [...]

Evaluation a.size() evaluates the id expression a , which "refers to a variable ... of reference type" and does not have a previous initialization. Therefore, this is not a basic constant expression, but not a constant expression.

+7
source share

All Articles