Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 874
einpoklum Avatar asked Aug 20 '17 14:08

einpoklum


People also ask

Can std :: function be Constexpr?

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.

Can strings be Constexpr?

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!


1 Answers

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.

like image 159
T.C. Avatar answered Oct 07 '22 20:10

T.C.