C ++ template factorial computation

Let's say I have this code:

template <int n>
class Factorial
{
    public:
        static const int f = Factorial<n-1>::f*n;
};
template<>
class Factorial<0>
{
    public:
        static const int f =1;
};

      

This is the template for calculating the factorial. It must be evaluated at compile time. Is it generally reasonable (in particular: faster) to do computation with templates at compile time? Postscript Sorry if this has been asked and answered before, I searched for this specific question and only found similar ones.

+3


source to share


1 answer


If you can compute something at compile time, you should, as long as it doesn't complicate your code. Typically, the compiler will compute constant subexpressions at compile time for you. However, the computation you are showing is different from what templates use as a complete Turing programming system .



This particular pattern is intended to provide a trivial demonstration of how to compute something at compile time. The program is very similar to the Prolog program: it consists of a trivial base case and a recursive recovery step. The problem with such programs is that they are very difficult to understand. While there are times when compile-time computation helps you build robust software, the applicability of these techniques is limited by the significant maintenance obligations they create.

+4


source







All Articles