Any function consisting only of a return statement can be declared constexpr and, thus, will be evaluated at compile time if all arguments are constexpr , and only constexpr functions constexpr called in their body. Is there a reason why not declare such a constexpr function?
Example:
constexpr int sum(int x, int y) { return x + y; } constexpr i = 10; static_assert(sum(i, 13) == 23, "sum correct");
Can someone provide an example in which declaring a constexpr function would do some harm?
Some initial thoughts:
Even if there should be no good reason for declaring a function not constexpr I could assume that the constexpr keyword has a transitional role: its absence in code that does not require compilation time estimates will allow compilers that do not implement evaluation compilation time to compile this code ( but with a reliable rejection of the code that needs them, as is done using constexpr ).
But I do not understand: if there should not be good reason for ever declaring a function not constexpr , why not every function in the standard library is declared constexpr ? (You cannot argue that this has not been done yet, because there has not yet been enough time to do it, because doing it for everyone is not a problem - contrary to the solution for each individual function, if you make it constexpr or not). --- I know that N2976 intentionally does not require cstrs for many standard types of libraries, such as containers, as this would be too restrictive to the possible implementation. Let's exclude them from the argument and just ask ourselves: as soon as the type of the standard library has constexpr cstr, why did every function working on it declare constexpr ?
In most cases, you also cannot argue that you can not declare a constexpr function simply because you do not plan to use compilation time: because if other evtl. will use your code, they may see such use that you are not. (But provided, of course, for type types, type types, etc.)
So, I think there should be a good reason and a good example for intentional not declaring a constexpr function?
(with “every function” I always mean: every function that meets the requirements for constexpr , that is, defined as single return, takes only type arguments with constexpr cstrs and calls only constexpr functions.)
Question Why constexpr std::forward discard constexpr -ness? is a special case of this.