PKU C + + programming Practice Learning Note 4 file operations and templates

Source: Internet
Author: User
Tags int size

Seventh. File Operations and templates

7.1 File Operations


7.2 Function templates

Generic Programming (Generic programming)

The type of data to be manipulated is not specified when the algorithm is implemented

generics --algorithm implementation once, applicable to a variety of data structures

Advantage: Reduce duplication of code writing

Two types of

    • function templates
    • Class template
Parallel to abstract, encapsulation, inheritance, polymorphism


function templates

Template<class type parameter 1, class type parameter 2, ... > Return value type template name (formal parameter list) {  function Body}
example, a function template for exchanging two variable values

Template <class t>void Swap (t & x,t & y) {  t tmp = x;  x = y;  y = tmp;} int main () {  int n = 1, M = 2;  Swap (n, m); The compiler automatically generates void Swap (int & int &) functions  double f = 1.2, G = 2.3;  Swap (f, g); The compiler automatically generates void Swap (double &, double &) function  return 0;}
Function templates can be overloaded, as long as their formal parameter lists are different

The following two templates can exist at the same time:

Template<class T1, class t2> void print (T1 arg1, T2 arg2) {   cout<< arg1 << "" << arg2<<e Ndl } template<class t> void print (t arg1, t arg2) {   cout<< arg1 << "" << arg2<<endl;}
The C + + compiler follows the following precedence order:

    • Step 1: Find the normal function with exact matching parameters (functions not instantiated by template)
    • Step 2: Re-find the template function with exact matching parameters
    • Step 3: Re- find the common function that can be matched after automatic type conversion
    • Step 4: The above can not be found, the error
Example: function template invocation Order

Template <class t>t max (t A, T b) {  cout << template Max 1 <<endl;  return 0;} Template <class T, class t2>t Max (T A, T2 b) {  cout << Template Max 2 <<endl;  return 0;} Double Max (double A, double b) {  cout << "Mymax" << Endl;  return 0;} int main () {  int i=4, j=5;  Max (1.2,3.4); Call the Max (double, double) function  max (i, j);//Call the function generated by the first T Max (t A, T b) template  max (1.2, 3);//Call the function generated by the second T Max (t A, T2 b) Template 
   return 0;}
Assignment compatibility principle causes the ambiguity of type parameters in function templates

Template<class t>t myFunction (t arg1, t arg2) {  cout<<arg1<< "" <<arg2<< "\ n";  return arg1;} ... myFunction (5, 7); Ok:replace T with Intmyfunction (5.8, 8.4); Ok:replace T with Doublemyfunction (5, 8.4); Error:replace T with int or double? Ambiguity
You can use more than one type parameter in a function template to avoid ambiguity

Template<class T1, Class T2>t1 myFunction (T1 arg1, T2 arg2) {  cout<<arg1<< "" <<arg2<< "\ n";  return arg1;} ... myFunction (5, 7); Ok:replace T1 and T2 with Intmyfunction (5.8, 8.4); Ok:replace T1 and T2 with Doublemyfunction (5, 8.4); Ok:replace T1 with int, T2 with double

Class 7.3 Templates


The class template defines the C + + class template as follows:
Template < type parameter table >class class templates name {  member function and member variable};
The type parameter table is written as follows:
class type parameter 1, class type parameter 2, ...
A member function in a class template, if defined outside the class template:
Template < type parameter table > return value type <span style= "color: #3333ff;" > class template name < type parameter names list ></span>:: member function name (parameter table) {  ...}
To define an object with a class template, use the following syntax:
Class template name < real type parameter table > object name (constructor actual parameter table);
If the class template has a parameterless constructor, you can also write only:
Class template name < real type parameter table > object name;
Example
Pair class Templates: Template <class T1, class T2>class pair{public:<span style= "White-space:pre" ></span>t1 Key Keyword <span style= "white-space:pre" ></span>t2 value; Value <span style= "White-space:pre" ></span>pair (T1 k,t2 v): Key (k), value (v) {};<span style= "White-space: Pre "></span>bool operator < (const pair<t1,t2> & P) const;}; Template<class t1,class t2>bool pair<t1,t2>::operator< (const PAIR<T1, T2> & P) const// The member function of the Pair operator <{return key < P.key,} The use of the//pair class template: int main () {  pair<string, int> student ("Tom", 19);  //Instantiate a class pair<string, int>  cout << student.key << "" << Student.value;  return 0;} Output Result: Tom 19
Declaring an object compiler by using a class template The process of generating a class from a class template is calledinstantiation of a class template
    • The compiler automatically replaces the type parameter in the class template with the specific data type, generating the code for the template class

Classes called template classes that are instantiated by class templates

    • Different data types specified for type parameters, different template classes obtained

The two template classes of the same class template are incompatible
pair<string, int> * p; pair<string, double> a;p = & A; Wrong
function templates as class template members
#include <iostream>using namespace std;template <class t>class a{public:   template<class t2>   void Func (T2 t) {cout << t;}//member function template};int main () {  a<int> A;  A.func (' K '); The member function template func is instantiated with  return 0;} Program output: K
Note that the type parameters of the class template, and the type parameters of the member function template, are not consistent.

If the function template is changed to templates <class t>void Func (T-t) {cout<<t} will error "declaration of ' Class T ' Shadows template Parm ' class T '"

The parameter declarations for class templates and non-type parameter class templates can includenon-type parametersSuch as:
Template <class T, int elementsnumber>
    • Non-type parameter: Used to describe a property in a class template
    • Type parameters: Used to describe attribute types in class templates, parameter types for member operations, and return value types
The < of the class templatetype parameter TableNon-type parameters can occur in >:
Template <class T, int size>class carray{t array[size];p ublic:void Print () {for   (int i = 0; i < size; ++i)   cout << array[i] << Endl;}; Carray<double, 40> A2; Carray<int, 50> A3; note:carray<int,40> and carray<int,50> are completely two classes. Objects of two classes cannot be assigned to each other










PKU C + + programming Practice Learning Note 4 file operations and templates

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.