Skip to content

Instantly share code, notes, and snippets.

@gcnyin
Created July 23, 2020 14:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gcnyin/d8b1d023a1b8fd3c798514fb94e6714f to your computer and use it in GitHub Desktop.
Save gcnyin/d8b1d023a1b8fd3c798514fb94e6714f to your computer and use it in GitHub Desktop.
C++ Compile-time factorial calculation
#include <iostream>
template <uint64_t n>
struct Fact {
static const uint64_t value = n * Fact<n - 1>::value;
};
template <>
struct Fact<1> {
static const uint64_t value = 1;
};
constexpr uint64_t fact(uint64_t n) { return n == 1 ? 1 : n * fact(n - 1); }
int main() {
std::cout << Fact<20>::value << std::endl;
std::cout << fact(20) << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment