Created
July 23, 2020 14:53
-
-
Save gcnyin/d8b1d023a1b8fd3c798514fb94e6714f to your computer and use it in GitHub Desktop.
C++ Compile-time factorial calculation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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