STL 中有copy 函数, 感觉的效率还可以提高些, 就试着使用模板推导的方式决定调用不同的函数,本事就是根据形参类型的不同而调用不同的函数 , 首先自定义最简单的2个类 , true_type 和 false_type , 详见如下代码, VS2008验证 OK
// algorithm.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <vector>
#include <list>
namespace algor{
struct true_type{};
struct false_type{};
template <typename T>struct iterator_trait{
typedef false_type value_type;
};
template <>struct iterator_trait<int*>{
typedef true_type value_type;
};
template <>struct iterator_trait<char*>{
typedef true_type value_type;
};
template <typename Iter1, typename Iter2>inline Iter2 t_copy(Iter1 first, Iter1 end, Iter2 out){
typedef iterator_trait<Iter1>::value_type value_type;
return copy_impl(first, end, out, has_trivial_assign<value_type>::value_type());
}
template <typename T>struct has_trivial_assign{
typedef T value_type;
};
template <typename T>T* copy_impl(T* first, T* end, T* out, true_type){
memmove(out, first, (end-first)*sizeof(T));
return out + (end - first);
}
template <typename Iter1, typename Iter2>Iter2 copy_impl(Iter1 first, Iter1 end, Iter2 out, false_type){
while(first != end)
{
*out = *first;
++first;
++out;
}
return out;
}
}
#define N 100000
struct MyFoo{
char c;
MyFoo& operator=(const MyFoo& f){
c = f.c;
return *this;
}
};
using namespace std;
using namespace algor;
int _tmain(int argc, _TCHAR* argv[])
{
MyFoo f;
vector<MyFoo> vect(N, f);
vector<MyFoo>::iterator first = vect.begin();
vector<MyFoo>::iterator end = vect.end();
list<MyFoo> t_list;
t_list.resize(N);
list<MyFoo>::iterator out = t_list.begin();
int arr[N] = {1,};
int brr[N] = {2,};
int* aarr = arr;
int* bbrr = brr;
t_copy(aarr, aarr+N, bbrr);
t_copy(first, end, out);
return 0;
}