I am implementing a binomial coefficient (n choose k) function in C++. Besides using a "normal" function (which is evaluated at runtime) this also can be accomplished using template metaprogramming (when the arguments are known at compile time):
template <unsigned int n, unsigned int k>
struct Binomialkoeffizient {
static const unsigned int value = Binomialkoeffizient<n, k-1>::value * (n-k+1) / k;
};
template <unsigned int n>
struct Binomialkoeffizient<n, 0> {
static const unsigned int value = 1;
};
The drawback of this implementation is, that it does not make use of the theorem n choose k = n choose n-k in the cases where k > n/2. So unnecessary arithmetic overflow may occur, e.g. 49 choose 43 does overflow, whereas 49 choose 6 does not.
I have tried the following to improve this:
template <unsigned int n, unsigned int k>
struct Binomialkoeffizient {
static const unsigned int value = (2*k > n) ? Binomialkoeffizient<n, n-k>::value : Binomialkoeffizient<n, k-1>::value * (n-k+1) / k;
};
template <unsigned int n>
struct Binomialkoeffizient<n, 0> {
static const unsigned int value = 1;
};
Unfortunately, I get fatal error: template instantiation depth exceeds maximum of 900
.
This seems to be caused by the fact, that the ternary operator is not evaluated during the process of recursive template instantiation.
What are possible alternatives to using ?:
?
I am interested in pre-C++11 solutions and newer solutions alike (maybe std::enable_if
helps, but I do not know well about it).
std::conditional
? – Electromagnetismstd::conditional
. Step 2: Writemy::conditional
in C++03. Step 3: Profit. – Ranged