Chiffa
Chiffa

Reputation: 1506

C++ template factorial computation

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;
};

It's a template that's meant to compute a factorial. It should be computed at compile time. Is it generally reasonable (specifically: quicker) to perform computations via templates at compile time? P.S. Sorry if this has been asked and answered before, I searched for this particualr question and only found similar ones.

Upvotes: 3

Views: 1609

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726639

If you can compute something at compile time, you should do that, unless this complicates your code a lot. Generally, the compiler will compute constant sub-expressions at compile time for you. The computation that you show, however, is different, because it uses templates as a Turing-complete programming system.

This particular template is meant to provide a trivial demo of how to compute something at compile time. The program looks very much like a Prolog program: it consists of a trivial base case and a recursive reduction step. The problem with programs of this kind is that they are remarkably hard to understand. Although there are situations when compile-time computations help you build reliable software, the applicability of these methods is limited because of significant maintenance liabilities that they create.

Upvotes: 4

Related Questions