construct()
和destroy()
construct()
使用了placement new
template<class T1,class T2> inline void construct(T1* p,const T2& value) { new (p) T1(value); }
destroy()
template<class ForwardIterator> inline void destroy(ForwardIterator first,ForwardIterator last) { __destroy(first,last,value_type(first)); };
利用了第三章中提到的__type_traits<>
获取合适的措施。
对于POD类型,则默认不采取任何措施。
__destroy_aux
template<class ForwardIterator> inline void __destroy_aux(ForwardIterator, ForwardIterator,__true_type) {};
出于性能?直接特化了char *
和wchar_t*
版本。省去找模板?
inline void destory(char*,char*) {}; inline void destory(wchar_t*,wchar_t*) {};
iterator_traits<T>
为了获取iterator所指内容的型别,有了iterator_traits
my_define.h
#ifndef CH1_MY_DEFINE_H #define CH1_MY_DEFINE_H template<class T> struct my_iterator_traits{ typedef typename T::value_type value_type; }; template<class T> struct my_iterator_traits<T*>{ typedef T value_type; }; #endif //CH1_MY_DEFINE_H
main.cpp
#include <iostream> #include <vector> #include "my_define.h" using namespace std; template<class I> typename my_iterator_traits<I>::value_type function(I a) { return *a; } int main() { int *aa = new int; *aa = 1; cout<< function(aa)<<endl; int a = 1; vector<int> arr(1,0); auto iter=arr.begin(); cout<< function(iter)<<endl; return 0; }
__type_traits<T>