您的位置:首页 > Web前端

Effective C++ Item 48 认识 template 元编程

2014-07-16 09:32 337 查看
本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie

经验:Template metaprogramming (TMP, 模板元编程)可将工作由运行期移往编译期,因而得以实现早期错误侦测和更高的执行效率

示例1:
template<typename IterT, typename DistT>
void advance(IterT &iter, DistT d){
if(typeid(typename std::iterator_traits<IterT>::iterator_catogory) == typeid(std::random_access_iterator_tag)){
iter += d;
}else{
if(d >= 0) { while(d--) ++iter;}
else {while(d++) --iter;}
}
}

std::list<int>::iterator iter;
advance(iter, 10); //当这里调用时,将会具体化出下面的函数

void advance(std::list<int>::iterator &iter, int d){
if(typeid(typename std::iterator_traits<std::list<int>::iterator>::iterator_catogory) == typeid(std::random_access_iterator_tag)){
iter += d; //编译出错。因为 std::list<int>::iterator 不支持 +=
}else{
if(d >= 0) { while(d--) ++iter;}
else {while(d++) --iter;}
}
}

解析:虽然不会执行 += 那一行,但编译器必须确保所有源码都有效。

纠正:融合重载技术后,traits classes 有可能在编译期对类型执行 if...else 测试 --> 见 Item 47

示例2:TMP主要是个函数式语言,主要涉及递归模板具体化
template<unsigned n>
struct Factorial{
enum {value = n * Factorial<n-1>::value }; //enum hack, 声明一个名为 value 的 TMP 变量来保存当前计算所得的阶乘值
};

template<> //全特化。 当 Factorial<0> 的值是1
struct Factorial<0>{
enum {value = 1};
};

int main(){
std::cout << Factorial<5>::value;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: