C ++ primer (11)-templates and generic programming

Source: Internet
Author: User

Generic programming, like object-oriented programming, relies on some form of polymorphism. The polymorphism on which Object-Oriented Programming depends is called Runtime polymorphism, And the polymorphism on which generic programming depends is called compilation Polymorphism or parametric polymorphism.

In generic programming, the classes and functions we write can be used polymorphism across unrelated types during compilation. A class or function can be used to manipulate multiple types of objects. Containers, iterators, and algorithms in the standard library are examples of good generic programming.

Templates are the basis of generic programming.

Example of a template function

First, let's look at a piece of code for comparing the sizes.

#include<iostream>using namespace std;int compare(const int &v1,const int &v2);double compare(const double &v1,const double &v2);int main(){cout<<"Hello"<<endl;cout<<compare(1,2)<<compare(1.2,3.2)<<endl;    return 1;}int compare(const int &v1,const int &v2){cout<<"compare int"<<endl;if (v1<v2) return -1;if(v2<v1) return 1;return 0;}double compare(const double &v1,const double &v2){cout<<"compare double"<<endl;if (v1<v2) return -1;if(v2<v1) return 1;      return 0;}

The results after compilation and running are as follows:

In the above program, the Compare function is overloaded. Because of different parameters, the final called function will automatically match.

Now let's assume that the Compare function not only supports int and double, but also supports float, string... to continue to reload, no. Now you need the template function.

Modify the source program.

#include<iostream>#include<string>using namespace std;template <typename T>int compare(const T &v1,const T &v2){if(v1<v2) return -1;if(v1>v2) return 1;return 0;}int main(){    cout<<"Hello"<<endl;    string a="zoo",b="tiger";    cout<<compare(a,b)<<compare(1,2)<<compare(1.2,3.2)<<endl;    return 1; }

Running result:

This is the legendary template function. When using the function template, the compiler will infer which template is bound to the template parameter. Once the compiler determines the actual template parameters, it is called an instance of the function template.

The compiler uses real parameters to replace the corresponding template parameters and compiles the revised functions.

Therefore, three compare versions are compiled above. The dirty and tiring compiler has already helped us.

Note that the name used as the template parameter cannot be reused within the template.

Operations completed within the loaded function template limit the types of function quotas that can be instantiated and modified. The programmer's responsibility is to ensure that the type used as the real parameter of the function actually supports any operation used, and that the operations in the environment where the template uses those operations are normal.

Pay attention to the following points when using the template:

1) As few requirements as possible for the real parameter type;

2) The template parameter is referenced by const;

3) the test in the function body only uses <comparison.

Replace # define with template inline

We often use # define to define macros, such:

#define CALL_WITH_MAX(a,b) f((a)>(b))?(a):(b);

Although the above statement is very careful with a lot of parentheses, but... if the statement is like this:

 int main()  {      int a=5,b=3;      CALL_WITH_MAX(++a,b);      cout<<"a"<<a<<"b"<<b<<endl;      CALL_WITH_MAX(++a,b+10);      cout<<"a"<<a<<"b"<<b<<endl;      cout<<"Hello"<<endl;      return 1;  }

The running result is as follows:

Call_with_max is called for the first time, and a is added twice. A is added only once for the second time. Therefore, it is not safe.

The template is used below.

#include<iostream>using namespace std;//#define CALL_WITH_MAX(a,b) (a)>(b)?(a):(b);template <typename T>inline T call_with_max(const T &a,const T &b){return(a>b?a:b);}int main(){int x,a=5,b=3;x=call_with_max(++a,b);cout<<"a"<<a<<"b"<<b<<"x"<<x<<endl;call_with_max(++a,b+10);cout<<"a"<<a<<"b"<<b<<endl;cout<<"Hello"<<endl;return 1;}

Running result:

This is our expected result.

Class Template

The following is a simple array template.

#include<iostream>#include <stdlib.h>using namespace std;template <class T>  class Array  {      public:          Array(int);          T & operator[] (int);          int getSize();          ~Array();      private:          T *a;          int size;          int errorValue;          Array();  };    template<class T>  Array<T> ::Array(int n)  {      a = new T[size = n];      errorValue = -1;  }    template<class T>  Array<T> ::~Array()  {      delete []a; }  template<class T>  T& Array<T>::operator[](int index)  {      if(index < 0 || index >= size)      {          cout << "Out of boundry" << endl;          exit(1);    }      return a[index];  }    template<class T>  int Array<T>::getSize()  {      return size;  }  int main(){Array<double> a(10);Array<int> b(20);cout<<"a.size:"<<a.getSize()<<endl;for(int i=0;i<b.getSize();i++)cout<<b[i]<<endl;return 1;}

Running result:

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.