Template derivation improves program efficiency and template derivation Efficiency

Source: Internet
Author: User

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

  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.