I've been reading a book about C++14/11. I just finished reading a chapter about the constexpr
keyword. I know what it's used for, but how often should I use constexpr
? Should I use it even in code for classes I know will never be used to create contstexpr
objects? (Just in case, because it doesn't cost me anything, right?)
C++14 How often should I use constexpr?
There's an extensive discussion in item 15 (Use constexpr whenever possible) of the Scott Meyer's book Effective Modern C++.
The outline of this item is that constexpr
should be used whenever possible, due to the fact that constexpr
functions and objects can be used in a wider range of contexts than the non-constexpr
ones.
However, in the same item the author mentions a caveat of overusing constexpr
. That is, if you decide to qualify an object or a function as constexpr
your clients will be allowed to use it in constexpr
contents. However, if you later decide that this code must not be constexpr
and remove constexpr
, this can cause your code not to compile including the side effects that this will have to your clients.
Quoting from original text:
“Use constexpr whenever possible” is your willingness to make a long-term commitment to the constraints it imposes on the objects and functions you apply it to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With