Template derivation improves program efficiency and template derivation Efficiency
The STL contains the copy function, which improves the efficiency. We try to use the template derivation method to call different functions. The skill is to call different functions based on different types of parameters, first, define the simplest two classes, true_type and false_type. For details, refer to the following code.
// 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 100000struct 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;}