template <class InputIterator, class OutputIterator> // 泛化版本 inline OutputIterator copy(InputIterator first, InputIterator last, OutputIterator result) { return __copy_dispatch<InputIterator,OutputIterator>()(first, last, result); } inline char* copy(const char* first, const char* last, char* result) { // 针对原生指针的重载 memmove(result, first, last - first); return result + (last - first); } inline wchar_t* copy(const wchar_t* first, const wchar_t* last, // 针对原生指针的重载 wchar_t* result) { memmove(result, first, sizeof(wchar_t) * (last - first)); return result + (last - first); }
template <class InputIterator, class OutputIterator> // 泛化版本 struct __copy_dispatch { OutputIterator operator()(InputIterator first, InputIterator last, OutputIterator result) { return __copy(first, last, result, iterator_category(first)); } }; template <class T> struct __copy_dispatch<T*, T*> // 特化版本 { T* operator()(T* first, T* last, T* result) { typedef typename __type_traits<T>::has_trivial_assignment_operator t; return __copy_t(first, last, result, t()); } }; template <class T> struct __copy_dispatch<const T*, T*> // 特化版本 { T* operator()(const T* first, const T* last, T* result) { typedef typename __type_traits<T>::has_trivial_assignment_operator t; return __copy_t(first, last, result, t()); } };
template <class InputIterator, class OutputIterator> inline OutputIterator __copy(InputIterator first, InputIterator last, OutputIterator result, input_iterator_tag) // 输入迭代器 { for ( ; first != last; ++result, ++first) *result = *first; return result; } template <class RandomAccessIterator, class OutputIterator> inline OutputIterator __copy(RandomAccessIterator first, RandomAccessIterator last, OutputIterator result, random_access_iterator_tag) // 随机迭代器 { return __copy_d(first, last, result, distance_type(first)); }
template <class RandomAccessIterator, class OutputIterator, class Distance> inline OutputIterator __copy_d(RandomAccessIterator first, RandomAccessIterator last, OutputIterator result, Distance*) { for (Distance n = last - first; n > 0; --n, ++result, ++first) *result = *first; return result; }
template <class T> inline T* __copy_t(const T* first, const T* last, T* result, __true_type) { // trivial memmove(result, first, sizeof(T) * (last - first)); return result + (last - first); } template <class T> inline T* __copy_t(const T* first, const T* last, T* result, __false_type) { // non-trivial return __copy_d(first, last, result, (ptrdiff_t*) 0); }
原文:http://blog.csdn.net/nestler/article/details/25775863