Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 269
Chiffa Avatar asked Sep 06 '26 03:09

Chiffa


1 Answers

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.

like image 120
Sergey Kalinichenko Avatar answered Sep 07 '26 17:09

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!