Skip to content

Instantly share code, notes, and snippets.

@nekko1119
Last active December 20, 2015 12:39
Show Gist options
  • Save nekko1119/6133074 to your computer and use it in GitHub Desktop.
Save nekko1119/6133074 to your computer and use it in GitHub Desktop.
C++のメタプログラミングにおけるhello worldポジションこと、階乗を求めるfactorial関数、数値でのメタ関数としてはよく見るけど、型のメタ関数として書いたことがなかったので試しに書いてみた
#include <boost/mpl/int.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/multiplies.hpp>
#include <boost/mpl/equal_to.hpp>
using namespace boost;
template <class I>
struct factorial
: mpl::eval_if
<
mpl::equal_to<I, mpl::int_<0>>,
mpl::int_<1>,
mpl::multiplies<I, factorial<typename I::prior>>
>
{};
#include <iostream>
using namespace std;
int main()
{
cout << factorial<mpl::int_<5>>::value << endl;
}
//見慣れた数値でのメタ関数
template <int N>
struct fact
{
static const int value = N * fact<N - 1>::value;
};
template <>
struct fact<0>
{
static const int value = 1;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment