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

- 1,328
- 14
- 30
-
You ask for opinions. From my point if view, you should use it as often as you can. Someone might have different thoughts. – George Sovetov Apr 03 '16 at 20:37
-
@GeorgeSovetov Problem is that 'opinions' are off-topic here (_primarily opinion based_ category). – edmz Apr 03 '16 at 20:40
-
4Early and often. And twice on Sundays. – wally Apr 03 '16 at 20:40
-
@black That's what I'm talking about. – George Sovetov Apr 03 '16 at 20:43
-
I know this is not the time nor place, but let me just say: I find it dumb that this site considers it off-topic to ask for opinions (even opinions like this), because, why wouldn't i want to hear an opinion of someone who is much better and more experienced than me? – Enn Michael Apr 03 '16 at 20:47
-
@TheodorosChatzigiannakis _"Opinions aren't off-topic"_ Huh? – πάντα ῥεῖ Apr 03 '16 at 21:13
-
1@TheodorosChatzigiannakis Of course every answer is subjective - humans can't reason otherwise. But there is at least a _minimum_ of objectiveness at the bottom: _facts_ rather than _opinions_. Here I wouldn't know how to write an answer. It is _way_ too dependent on OP's code, something we can't control. – edmz Apr 03 '16 at 21:17
-
1IOW, how would you say flatmouse's answer is wrong? – edmz Apr 03 '16 at 21:19
1 Answers
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.

- 41,839
- 11
- 94
- 168