Should we use constexpr everywhere we can?
Why I don't bother to try and put constexpr
at every opportunity in list form, and in no particular order:
- I don't write one-liner functions that often
- when I write a one-liner it usually delegates to a non-constexpr function (e.g.
std::get
has come up several times recently) - the types they operate on aren't always literal types; yes, references are literal types, but if the referred type is not literal itself I can't really have any instance at compile-time anyway
- the type they return aren't always literal
- they simply are not all useful or even meaningful at compile-time in terms of their semantics
- I like separating implementation from declaration
Constexpr functions have so many restrictions that they are a niche for special use only. Not an optimization, or a desirable super-set of functions in general. When I do write one, it's often because a metafunction or a regular function alone wouldn't have cut it and I have a special mindset for it. Constexpr functions don't taste like other functions.
I don't have a particular opinion or advice on constexpr
constructors because I'm not sure I can fully wrap my mind around them and user-defined literals aren't yet available.
It won't bother the compiler. The compiler will (or should anyway) give you a diagnostic when/if you use it on code that doesn't fit the requirements of a constexpr
.
At the same time, I'd be a bit hesitant to just slap it on there because you could. Even though it doesn't/won't bother the compiler, your primary audience is other people reading the code. At least IMO, you should use constexpr
to convey a fairly specific meaning to them, and just slapping it on other expressions because you can will be misleading. I think it would be fair for a reader to wonder what was going on with a function that's marked as a constexpr
, but only used as a normal run-time function.
At the same time, if you have a function that you honestly expect to use at compile time, and you just haven't used it that way yet, marking it as constexpr
might make considerably more sense.