Monday, June 27, 2016

Factorial via template metaprogramming

Here is an example implementation of factorial via template metaprogramming:

#include <iostream>
template <int N>
struct fact
{
static const int value = N * fact<N - 1>::value;
};
template <>
struct fact<0>
{
static const int value = 1;
};
int main()
{
std::cout << fact<6>::value << std::endl;
std::cout << fact<3>::value << std::endl;
return 0;
}
view raw fact.cpp hosted with ❤ by GitHub

No comments:

Post a Comment