Back to TILs

C++ templates

Date: 2020-12-16Last modified: 2024-11-02

Table of contents

int factorial(const int input, const int sum = 1) {
  if (input > 1) {
    return factorial(input - 1, sum * input);
  }
  return sum;
}

template <int input, int sum = 1>
struct Factorial : Factorial<input - 1, input * sum> {};

template <int sum>
struct Factorial<1, sum> {
  enum { value = sum };
};

int main() {
  fmt::print("5! = {}\n", factorial(5));
  fmt::print("Factorial<4> = {}\n", int(Factorial<4>::value));
  fmt::print("Factorial<5> = {}\n", int(Factorial<5>::value));
  return 0;
}

Possible output

5! = 120
Factorial<4> = 24
Factorial<5> = 120