本文为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)) ... }
解析:上面 iterator_traits<IterT>::iterator_category 在编译期就可确定,但 if 语句却是在运行期才会核定,浪费时间,也造成可执行文件的膨胀。
纠正:融合重载技术后,traits classes 有可能在编译期对类型执行 if...else 测试
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 表现类型信息
时间: 2024-10-09 21:57:43