Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++14 How often should I use constexpr?

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

like image 573
Enn Michael Avatar asked Apr 03 '16 20:04

Enn Michael


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.

like image 130
101010 Avatar answered Oct 31 '22 16:10

101010