It's very natural to want to compare std::array
's at compile time; and its operator==()
is obviously constexpr
'able. Yet - it isn't marked constexpr
. Is this intentional or an oversight? And - what's the reason it was left that way (apparently in C++17 as well)?
Constexpr constructors are permitted for classes that aren't literal types. For example, the default constructor of std::unique_ptr is constexpr, allowing constant initialization.
constexpr std::string While it's best to rely on string_views and not create unnecessary string copies, the example above shows that you can even create pass vectors of strings inside a constexpr function!
P0031 explained why it didn't propose constexpr
comparisons:
Currently comparisons and
swap
/fill
may be implemented with the help of algorithms from<algorithm>
header. Marking comparisons with constexpr will break that ability and will potentially lead to performance degradations.
For example, ==
can be implemented in terms of std::equal
, which - in appropriate cases - can call the highly-optimized-but-decidedly-not-constexpr
memcmp
. Making constexpr
for ==
will rule out this optimization without special compiler assistance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With