n!階乗計算例
template練習メモです.
factorial.cpp
// n! 階乗計算 =====================================
#include <iostream>
using namespace std;
/// ------------------------------------------
/// 階乗計算を行う
/// factorial<N>()関数テンプレート定義
/// ------------------------------------------
template<int N>
int factorial(){
return factorial<N-1>() * N;
}
template<> /// 特殊化:factorial<N=”1”>だったら,値を返す
int factorial<1>(){
return 1;
}
/// ------------------------------------------
int main(){
cout << factorial<1>() << endl; /// Ans 1! = 1
cout << factorial<3>() << endl; /// 3! = 6
cout << factorial<4>() << endl; /// 4! = 24
cout << factorial<10>() << endl; /// 10! = 3628800
}
##実行結果
clang++ -std=c++11 factorial.cpp
./a.out
1
6
24
3628800