Skip to content

Instantly share code, notes, and snippets.

@mhepeyiler
Last active November 13, 2020 13:43
Show Gist options
  • Save mhepeyiler/8149576eda5175c510bfec44d7735cfb to your computer and use it in GitHub Desktop.
Save mhepeyiler/8149576eda5175c510bfec44d7735cfb to your computer and use it in GitHub Desktop.
Compile time factorial function implemenetation. It uses template specialization and variable template. Thus, it needs to be compiled above C++17.
template<unsigned long long n>
constexpr unsigned long long Factorial = n * Factorial<n - 1>;
template<>
constexpr unsigned long long Factorial<0> = 1;
int main()
{
constexpr auto fact_5 = Factorial<5>; // 120
constexpr auto fact_7 = Factorial<7>; // 5040
constexpr auto fact_20 = Factorial<20>; // 2432902008176640000
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment