Deduce non-type template parameter

Your current code would normally be written as follows, I believe:

constexpr factorial (int n)
{
    return n > 0 ? n * factorial( n - 1 ) : 1;
}

If you call it with a constant-expression, such as factorial(5), then all the compiler magic will come into play. But if you do int a = 3; factorial(a), then I think it will fall back on a conventional function - i.e. it won't have built a lookup table of pre-computed answers.

In general, you should mark every function and constructor as constexpr if you can. You lose nothing, the compiler will treat it as a normal function if necessary.


Can't be done, unless you have a time machine.

The parameter to the function is handled at runtime. Yes, in your case it's a literal constant, but that's a special case.

In function definitions, the parameter types are fixed at compile-time (and thus, can be used to deduce template parameters), but parameter values are only fixed at runtime.

Why do you need this? Is it just so you don't have to type the <>'s?