Sobes.tech
Junior — Senior

Compile-time factorial calculation using C++ templates

livecode

Task condition

The task is to implement a template class Fac<N> that computes the factorial of the number N at compile time using recursive template specialization. You need to demonstrate that the resulting value is indeed computed at compile time.

template <unsigned N>
class Fac;

template <unsigned N>
class Fac<N> {
    static constexpr int result = Fac<N - 1>::result * N;
};

template <>
class Fac<0> {
    static constexpr int result = 1;
};

Check that Fac<5>::result equals 120 and that the computation occurs at compile time (for example, using static_assert).