Skip to content

Instantly share code, notes, and snippets.

@odeblic
Last active July 27, 2017 11:25
Show Gist options
  • Save odeblic/3bf667da7afd0f7bcd87f9089926dae1 to your computer and use it in GitHub Desktop.
Save odeblic/3bf667da7afd0f7bcd87f9089926dae1 to your computer and use it in GitHub Desktop.
Metaprogramming with compile-time computed fibonacci and factorial functions
#include <iostream>
template <unsigned int N>
struct factorial
{
enum { value = N * factorial<N - 1>::value };
};
template <>
struct factorial<0>
{
enum { value = 1 };
};
template <int N>
constexpr int fibonacci()
{
return fibonacci<N-1>() + fibonacci<N-2>();
}
template <>
constexpr int fibonacci<0>()
{
return 1;
}
template <>
constexpr int fibonacci<1>()
{
return 1;
}
int main()
{
//std::cout << "f(-1) -> " << fibonacci<-1>() << "\n"; // compile error
std::cout << "f(0) -> " << fibonacci<0>() << "\n";
std::cout << "f(1) -> " << fibonacci<1>() << "\n";
std::cout << "f(2) -> " << fibonacci<2>() << "\n";
std::cout << "f(3) -> " << fibonacci<3>() << "\n";
std::cout << "f(4) -> " << fibonacci<4>() << "\n";
std::cout << "f(5) -> " << fibonacci<5>() << "\n";
//std::cout << "-1! -> " << factorial<-1>::value << "\n"; // compile error
std::cout << "0! -> " << factorial<0>::value << "\n";
std::cout << "1! -> " << factorial<1>::value << "\n";
std::cout << "2! -> " << factorial<2>::value << "\n";
std::cout << "3! -> " << factorial<3>::value << "\n";
std::cout << "4! -> " << factorial<4>::value << "\n";
std::cout << "5! -> " << factorial<5>::value << "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment