C ++ 14 How often should constexpr be used?

I read a book about C ++ 14/11. I just finished reading the chapter on the constexpr keyword. I know what it is used for. I get how this can be used for classes and class functions. But how often should I use constexpr? Should I even use it in code for classes that I know will never be used to create contstexpr objects? (Just in case, because it costs me nothing, right?)

+5
source share
1 answer

C ++ 14 How often should constexpr be used?

There is a thorough discussion in paragraph 15 (Use constexpr whenever possible) of the book Effective Modern C ++ .

The contour of this element is that constexpr should be used whenever possible, because constexpr functions and objects can be used in a wider range of contexts than non constexpr .

However, in the same paragraph, the author mentions a constexpr abuse constexpr . That is, if you decide to qualify an object or function as constexpr , your clients will be allowed to use them in constexpr . However, if you later decide that this code should not be constexpr and remove constexpr , this may result in your code not compiling, including the side effects that this will have for your clients.

Quote from source:

โ€œUse constexpr whenever possibleโ€ is your willingness to make a long-term commitment to the constraints that it imposes on objects and to which you apply.

+6
source

Source: https://habr.com/ru/post/1246360/


All Articles