标签:style blog http color 使用 文件
本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie
经验:Traits classes 使得"类型相关信息"在编译期可用。它们以 templates 和 "templates 特化"完成实现
示例:template<...> class deque{ public: class iterator{ public: typedef random_access_iterator_tag iterator_category; }; }; //template template<typename IterT> struct iterator_traits{ typedef typename IterT::iterator_category iterator_category; }; //template 偏特化 template<typename IterT> struct iterator_traits<IterT *> // template 偏特化,限制 IterT 必须是指针 { typedef random_access_iterator_tag iterator_category; }; //实现 advance template<typename IterT, typename DistT> void advance(IterT &iter, DistT d){ if(typeid(typename std::iterator_traits<IterT>::iterator_category) == typeid(std::random_access_iterator_tag)) ... }
template<typename IterT, typename DistT> void advance(IterT &iter, DistT d){ doAdvance(iter, d, typename std::iterator_traits<T>::iterator_category()); } template<typename IterT, typename DistT> void advance(IterT &iter, DistT d, std::random_access_iterator_tag){ iter += d; } template<typename IterT, typename DistT> void advance(IterT &iter, DistT d, std::bidirectional_iterator_tag){ if(d >= 0){while(d--) ++iter;} else{while(d++) --iter;} } template<typename IterT, typename DistT> void advance(IterT &iter, DistT d, std::input_iterator_tag){ if(d < 0) throw std::out_of_range("Negative distance"); while(d--) ++iter; }
Effective C++ Item 47 请使用 traits classes 表现类型信息,布布扣,bubuko.com
Effective C++ Item 47 请使用 traits classes 表现类型信息
标签:style blog http color 使用 文件
原文地址:http://blog.csdn.net/zhengsenlie/article/details/37807459