简介
- 模板元编程(Template Metaprogram)是C++11引入的编程范式(在Google Chromium源码中使用了很多模板元编程)
- 模板元程序在编译期执行。因此,合理利用它可以为你的程序“加速”。
- 模板元程序不能操作运行时变量和语(因为其在编译期执行)。
- 缺点:复杂,编写较为困难,维护起来也比较困难。
- 优点:加速你的程序,精简代码等等。
模板元的组成
- 模板元程序由元数据和元函数组成。
- 元数据:模板元程序可操作的数据,就是C++编译期可操作的数据(如:静态常量、枚举常量、基本类型、自定义类型等等)。
- 元函数:操作元数据的构件,可在编译期被调用。
小例
#include <iostream>
using namespace std;
template<class N, class M>
struct metaSize
{
static const int value = sizeof(N) + sizeof(M);
};
int main()
{
cout << metaSize<int, double>::value << endl;
}
#include <iostream>
using namespace std;
template<int Num1, int Num2>
struct metaValue
{
static const int value = Num1 + Num2;
};
int main()
{
cout << metaValue<1, 2>::value << endl;
}
- 对于运行时语法(如if else),C++11提供了模板元基础库type_traits,关于它的使用网上有很多资料。