lundi 2 mars 2015

Purpose of constexpr [duplicate]


This question already has an answer here:




This is more of a philosophical question rather than practical code snippet, but perhaps C++ gurus can enlighten me (and apologies if it's been asked already).


I have been reading Item 15 in Meyers's "Effective Modern C++" book, as well as this thread: implicit constexpr? (plus a reasonable amount of googling). The item goes over usage of constexpr for expressions, namely that it defines functions that can return compile time values given compile time inputs. Moreover, the StackOverflow thread I referred to shows that some compilers are perfectly capable of figuring out for themselves which function invocation results are known at compile time.


Hence the question: why was constexpr added to the standard as compared to defining when compilers should derive and allow static/compile-time values?


I realise it makes various compile-only (e.g. std::array<T, constexpr>) definitions less predictable, but on the other hand, as per Meyers's book, constexpr is a part of the interface,..., if you remove it, you may cause arbitrarily large amounts of client code to stop compiling. So, not only having explicit constexpr requires people to remember adding it, it also adds permanent semantics to the interface.


Aucun commentaire:

Enregistrer un commentaire