您的位置:首页 > 编程语言 > C语言/C++

c++模板元编程

2016-02-25 15:48 288 查看

元编程介绍

借助c++编译期模板展开逻辑生成c++代码的过程叫做模板元编程。对比c++语言本身,编译期间可以访问的数据叫做元数据,操作元数据的代码叫做元函数。

元数据

编译期可以感知的常量,如类型,整形常量(包括枚举变量,函数地址等)

元函数

meta_function_name<type-arguments>::type

meta_function_name<type-arguments>::value

定义一个函数:
template <int I>
struct Value {
typedef type int;
enum {value = I}
}

调用函数
int result = Value<10>::value;
typedef Value<10>::type value_type;


元编程应用

使用元编程可以在c++的编译器进行数值计算,类型检查,代码生成

数值计算

数值计算元函数返回结果是计算好的数值,标准访问方式是:meta_function_name<type-arguments...>::value
阶乘计算
template <int N>
struct Factorial {
enum {result = N*Factorial<N-1>::result};
};

template<>
struct Factorial<1> {
enum {result = 1};
};
int ret = Factorial<10>::result;
如果调用此函数计算阶乘,它的结果是在编译期间计算好然后再赋值给变量result
上面语句生成的汇编代码如下:



类型计算

类型计算元函数返回结果是类型,一般都是typedef出来的,标准访问方式是:meta_function_name<type-arguments...>::type

template <bool condition, typename T1, typename T2>
class IfThenElse {
typedef T1 ResultType;
}
template <false, typename T1, typename T2>
class IfThenElse {
typedef T2 ResultType;
}
typedef IfThenElse<true,int,char>::type ResultT;
类型的赋值只能通过typedef,类似于数值赋值采用=

代码生成

阶乘计算
template <int N>
struct Factorial2 {
static int Result() {
return N * Factorial2<N-1>::Result();
}
};

template<>
struct Factorial2<1> {
static int Result() {
return 1;
}
};
int ret = Factorial2<3>::Result();
上面的代码调用会产生循环展开代码,如下:

先调用Factorial2<3>::Result()



再调用Factorial2<2>::Result()



计算Factorial2<3>::Result()的结果用3*Factorial2<2>::Result()

小结:

元数据的引用会触发编译期计算(包括常量,类型)。

如果直接通过模板类定义对象,例如template_class_name<type-arguments> a,或者引用类的静态成员函数

[b]template_class_name<type-arguments>::func(a,b)。这些都会触发代码生成。

[/b]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: