As you probably know, C++11 introduces the constexpr
keyword.
C++11 introduced the keyword constexpr, which allows the user to guarantee that a function or object constructor is a compile-time constant. [...] This allows the compiler to understand, and verify, that [function name] is a compile-time constant.
My question is why are there such strict restrictions on form of the functions that can be declared. I understand desire to guarantee that function is pure, but consider this:
The use of constexpr on a function imposes some limitations on what that function can do. First, the function must have a non-void return type. Second, the function body cannot declare variables or define new types. Third, the body may only contain declarations, null statements and a single return statement. There must exist argument values such that, after argument substitution, the expression in the return statement produces a constant expression.
That means that this pure function is illegal:
constexpr int maybeInCppC1Y(int a, int b)
{
if (a>0)
return a+b;
else
return a-b;
//can be written as return (a>0) ? (a+b):(a-b); but that isnt the point
}
Also you cant define local variables... :( So I'm wondering is this a design decision, or do compilers suck when it comes to proving function a is pure?