Skip to content

C++20 constexpr std::complex errors #55370

@pkeir

Description

@pkeir

Though std::complex<>::operator+ (and others) are constexpr in C++20, the code below fails to compile.

#include <complex>

constexpr std::complex<double> x{1, 2};
constexpr std::complex<double> y = x + x;

I am using libstdc++ and note that the constexpr declarations are in place there, and also that g++ does compile it. I am on Ubuntu 21.10. Clang trunk also fails. The error message is below. I suspect it relates to constexpr support for __complex__.

$ clang++ -c -std=c++20 complex-constexpr.cpp 
complex-constexpr.cpp:4:32: error: constexpr variable 'y' must be initialized by a constant expression
constexpr std::complex<double> y = x + x;
                               ^   ~~~~~
/usr/bin/../lib/gcc/x86_64-linux-gnu/11/../../../../include/c++/11/complex:1336:13: note: subexpression not valid in a constant expression
          _M_value += __z.__rep();
                   ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/11/../../../../include/c++/11/complex:335:11: note: in call to '&__r->operator+=(x)'
      __r += __y;
          ^
complex-constexpr.cpp:4:38: note: in call to 'operator+(x, x)'
constexpr std::complex<double> y = x + x;
                                     ^
1 error generated.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions