c++ - Replacement for ternary operator in template metaprogramming -


i implementing binomial coefficient (n choose k) function in c++. besides using "normal" function (which evaluated @ runtime) can accomplished using template metaprogramming (when arguments known @ 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 implementation is, not make use of theorem n choose k = n choose n-k in cases k > n/2. unnecessary arithmetic overflow may occur, e.g. 49 choose 43 overflow, whereas 49 choose 6 not.

i have tried following 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, fatal error: template instantiation depth exceeds maximum of 900.

this seems caused fact, ternary operator not evaluated during process of recursive template instantiation.

what possible alternatives using ?: ?

i interested in pre-c++11 solutions , newer solutions alike (maybe std::enable_if helps, not know it).

c++11 introduced constexpr specifier,

...(which) declares possible evaluate value of function or variable @ compile time. such variables , functions can used compile time constant expressions allowed (provided appropriate function arguments given). constexpr specifier used in object declaration implies const.

(quoted http://en.cppreference.com/w/cpp/language/constexpr)

in practice, can implement function this:

template<class t> constexpr t binomial_coefficient(const t n, const t k) {     if ( 2 * k > n )     {         return binomial_coefficient(n, n - k);     }     else     {         return k ? binomial_coefficient(n, k - 1) * (n - k + 1) / k : 1;     } } 

that can evaluated @ compile time. example, @ https://godbolt.org/g/b1mgfd snippet compiled different compilers , line

constexpr auto value = binomial_coefficient(49, 43); 

become

mov     eax, 13983816 

Comments

Popular posts from this blog

javascript - Create a stacked percentage column -

Optimising Firebase database by automatically overwriting data -

javascript - Angular UI-Grid customTemplate directive causing rows to load slowly/? -