- // TMP_First.cpp : 定义控制台应用程序的入口点。
- //
- #include "stdafx.h"
- #include <iostream>
- //------------------------------------------------------------------------------
- // TMP的起手程序:编译期计算阶乘
- // 示范如何通过“递归模板具现化”实现循环,以及如何在TMP中创建和使用变量
- //------------------------------------------------------------------------------
- //------------------------------------------------------------------------------
- // 定义Factorial<n>
- //------------------------------------------------------------------------------
- template<unsigned n>
- struct Factorial
- {
- //一般情况:Factorial<n> = n*Factorial<n-1>
- enum { value = n * Factorial<n-1>::value };
- };
- template<>
- struct Factorial<0>
- {
- //特殊情况:Factorial<0> = 1
- enum { value = 1 };
- };
- //------------------------------------------------------------------------------
- // 使用Factorial<n>
- //------------------------------------------------------------------------------
- int _tmain(int argc, _TCHAR* argv[])
- {
- std::cout << Factorial<5>::value;
- return 0;
- }
TMP(Template metaprogramming)模板元编程的起手程序:编译期计算阶乘
最新推荐文章于 2024-01-30 13:59:13 发布