7

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

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
einpoklum
  • 118,144
  • 57
  • 340
  • 684

2 Answers2

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.

T.C.
  • 133,968
  • 17
  • 288
  • 421
  • 4
    Daniel Kruger says: This may be resolved when/if proposal [P0202](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0202r1.html) is adopted. – einpoklum Aug 20 '17 at 20:33
-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.

Marcus Müller
  • 34,677
  • 4
  • 53
  • 94
  • 1
    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.) – einpoklum Aug 20 '17 at 15:00
  • 1
    I'm having a hard time thinking of a templated constexpr function that deserves that name and deals with non-constexpr type members... – Marcus Müller Aug 20 '17 at 15:02
  • @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. – BigBoss Jan 04 '23 at 17:43