CG@CPPBLOG

/*=========================================*/
随笔 - 76, 文章 - 39, 评论 - 137, 引用 - 0
数据加载中……

《C++设计新思维》读书笔记(15)

2.10.2 侦测基本型别(略)'
2.10.3
优化的参数型别(略)
2.10.4 卸除饰词

下面是一个“const 卸除器

 1 template<typename T>
 2 class TypeTraits
 3 {
 4 private:
 5     template<class U> struct UnConst
 6     {
 7         typedef U Result;
 8     };
 9     template<class U> struct UnConst<const U>
10     {
11         typedef U Result;
12     };
13 public:
14     typedef UnConst<T>::Result NonConstType;
15 };

2.10.5 运用TypeTraits

这里实作一个调用BitBlast的例子: 

 1 enum CopyAlgoSelector{Conservative, Fast};
 2 
 3 // Conservative routine-works for any type
 4 template <typename InIt, typename OutIt>
 5 OutIt CopyImpl(InIt first, InIt last, OutIt result, Int2Type<Conservative>)
 6 {
 7     for(; first != last; ++first, ++result)
 8         *result = *first;
 9 }
10 
11 // Fast routine-works only for pointers to raw data
12 template <typename InIt, typename OutIt>
13 OutIt CopyImpl(InIt first, InIt last, OutIt result, Int2Type<Fast>)
14 {
15     const size_t n = last - first;
16     BitBlast(first, result, n * sizeof(*first));
17     return result + n;
18 }
19 
20 template<typename T> struct SupportsBitwiseCopy
21 {
22     enum{result = TypeTraits<T>::isStdFundamental};
23 }
24 
25 template <typename InIt, typename OutIt>
26 OutIt Copy(InIt first, InIt last, OutIt result)
27 {
28     typedef TypeTraits<InIt>::PointeeType SrcPointee;
29     typedef TypeTraits<OutIt>::PointeeType DestPointee;
30     enum { copyAlgo =
31         TypeTraits<InIt>::IsPointer &&
32         TypeTraits<OutIt>::IsPointer &&
33         SupportsBitwiseCopy<SrcPointee>::result &&
34         SupportsBitwiseCopy<DestPointee>::result &&
35         sizeof(SrcPointee) == sizeof(DestPointee) };
36     return CopyImpl(first, last, Int2Type<useBitBlast>);
37 }

对于一个POD结构(plain old data),即C struct,只有数据没有其它任何东西。因为无法甄别其类型,会调用慢速版本。我们可以这样做,让它调用快速版本,假如POD结构为Mytype

1 template<> struct SupportsBitwiseCopy<MyTyee>
2 {
3     enum {result = true};
4 };

posted on 2007-12-25 21:43 cuigang 阅读(304) 评论(0)  编辑 收藏 引用 所属分类: 《C++设计新思维》读书笔记


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理