Comment Re:Still half-assed C++11 support (Score 1) 198
My last post was a bit sparse on details but I'll try and improve upon it here. The main point I was trying to make was that just because you define a function as constexpr doesn't mean it will run at compile time unless certain conditions are met. This obviously isn't a bad thing as you can re-use the function at runtime.
If you have a constexpr function and all of its arguments are constant expressions (such as literals) and it is used in a constant expression (switch case label, array size, non-type template parameter, etc...) or to initialize a constexpr variable then it is guaranteed to run at compile time according to the standard. Otherwise it is up to the compiler. I've noticed a lot of people think that merely passing constant expressions to a constexpr function is enough to guarantee compile time evaluation, but it's not. For instance:
constexpr int factorial(int n) { return n <= 1 ? 1 : (n*factorial(n-1)); }
int main() {
char c[factorial(5)];
switch(n) {
case factorial(3):
break; }
constexpr int i = factorial(4);
cout << factorial(8) << endl;
int i;
cin >> i;
int j = factorial(i);
}
Here is a page that talks about it (especially in the comments). I was also mistaken about clang and gcc. At higher optimization levels the factorial of 8 will be computed at compile time rather than runtime.