2.10.2
偵測(cè)基本型別(略)'
2.10.3 優(yōu)化的參數(shù)型別(略)
2.10.4 卸除飾詞
下面是一個(gè)“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
運(yùn)用TypeTraits
這里實(shí)作一個(gè)調(diào)用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 }
對(duì)于一個(gè)POD結(jié)構(gòu)(plain old data),即C
struct,只有數(shù)據(jù)沒(méi)有其它任何東西。因?yàn)闊o(wú)法甄別其類型,會(huì)調(diào)用慢速版本。我們可以這樣做,讓它調(diào)用快速版本,假如POD結(jié)構(gòu)為Mytype。
1 template<> struct SupportsBitwiseCopy<MyTyee>
2 {
3 enum {result = true};
4 };