Why isn't std::array's operator==() marked constexpr?
Asked Answered
L

3

8

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)?

Lime answered 20/8, 2017 at 14:45 Comment(0)
C
9

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.

Clad answered 20/8, 2017 at 20:14 Comment(1)
Daniel Kruger says: This may be resolved when/if proposal P0202 is adopted.Lime
F
1

As of , operator== is constexpr for std::array by the acceptance of P1023.

Forsta answered 26/9 at 19:39 Comment(0)
A
-2

The rationale might be this: == of an array can only be a constexpr if the contained type's == is a constexpr, too.

Since the container can't enforce that, it can't (generally) offer a operator==() constexpr.

Asare answered 20/8, 2017 at 14:48 Comment(3)
The first sentence is true for any templated constexpr function which does anything with its template parameter. And - those can very well be made constexpr... so that is not it. (PS - Not my downvote.)Lime
I'm having a hard time thinking of a templated constexpr function that deserves that name and deals with non-constexpr type members...Ceraceous
@MarcusMüller constexpr for a templated function does not mean that the function is always constexpr, it just say this function may be constexpr for some types.Magnific

© 2022 - 2024 — McMap. All rights reserved.