Meta Programming

【本文链接】

http://www.cnblogs.com/hellogiser/p/meta-programming.html

【分析】

Template Mataprogram,中文叫模板元编程。我之能听说它,并对它不甚向往,主要是因为它有这样几个特点:
1、它编的程序不是运行的时候执行的,而是在编译的时候由编译器执行的;
2、它能够牵着编译器的鼻子走,靠的完全是符合标准的模板语法,不需要使用编译器的任何API;
3、它居然是图灵完备的,也就是说它什么事都能干。

【递归demo】

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 
#include <iostream>
using namespace std;

templateint n >
struct factorial
{
    
enum { ret = factorial < n - 1 >::ret * n };
};

template<>
struct factorial< 0 >
{
    
enum { ret = 1 };
};

int main()
{
    cout << 
"7! = " << factorial< 7 >::ret << endl; // 5040
    return 0;
}

【分支demo】

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 
template <bool C, typename Ta, typename Tb>
class IfThenElse;

template <typename Ta, typename Tb>
class IfThenElse<true, Ta, Tb>
{
public:
    
typedef Ta ResultT;
};

template <typename Ta, typename Tb>
class IfThenElse<false, Ta, Tb>
{
public:
    
typedef Tb ResultT;
};

【参考】

http://www.cppblog.com/youxia/archive/2008/08/30/60443.html

http://stackoverflow.com/questions/112277/best-introduction-to-c-template-metaprogramming

个人学习笔记,欢迎拍砖!---by hellogiser

Author: hellogiser
Warning: 本文版权归作者和博客园共有,欢迎转载,但请保留此段声明,且在文章页面明显位置给出原文连接。Thanks!
Me: 如果觉得本文对你有帮助的话,那么【推荐】给大家吧,希望今后能够为大家带来更好的技术文章!敬请【关注】
原文地址:https://www.cnblogs.com/hellogiser/p/meta-programming.html