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 };