Simplify the variation pattern: remove some specializations

I found a template for calculating the binomial coefficient, which I happily used to generate the function. The advantage is that I use this pattern to generate a compile-time Bernstein polynomial instead of using the resulting polynomials (5 very simple in total).

I originally thought the code would be simpler because now five random functions are generated. Unfortunately, the code below is hard to read for those not used for templates. Is there a way to get rid of at least some of the specialized templates?

// Template functions to estimate the binominal coefficient
template<uint8_t n, uint8_t k>
struct binomial {
  static constexpr int value = (binomial<n - 1, k - 1>::value + binomial<n - 1, k>::value);
};

template<>
struct binomial<0, 0> {
  static constexpr int value = 1;
};

template<uint8_t n>
struct binomial<n, 0> {
  static constexpr int value = 1;
};

template<uint8_t n>
struct binomial<n, n> {
  static constexpr int value = 1;
};

      

+3


source to share


1 answer


Perhaps you are perhaps using constexpr functions. Here is a C ++ 11-friendly version:

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

constexpr int bin_coeff(int n, int k)
{
    return factorial(n) / factorial(n - k) / factorial(k);
}

      



EXAMPLE

+4


source







All Articles