(11) Generic Programming/Function Templates/class templates

Source: Internet
Author: User

1. Generic Programming Basics

#include "iostream" using namespace std;void swap (int &a, int &b) {    int c;    c = A;    A = b;    b = C;} void swap (float &a, float &b) {    float C;    c = A;    A = b;    b = C;} void Main () {    int a = 1, b = 2;    Swap (A, b);    FLOAT A1 = 1, B1 = 2;    Swap (A1, B1);    

#include "iostream" using namespace std;//template keyword tells the C + + compiler, now begins generic programming//typename tells the C + + compiler that T is type (T is type, can be parameterized, int float) , you don't mess with the error//Type parameterization .... Template<typename t>void swap2 (t &a, T &b) {    T C;    c = A;    A = b;    b = C;} void  Main () {    ///generic programming is called in two//    automatic type derivation    int x = 1, y = 2;    SWAP2 (x, y);    printf ("x:%d y:%d \ n", x, y);    Float x1 = 1.0, y1 = 2.0;    Specific types call    swap2<float> (x1, y1);    printf ("X1:%f y1:%f \ n", x1, y1);    System ("Pause");}

2. function template Enhancement

#include "iostream" using namespace Std;template<typename t>void Sortarray (T *a, int num) {    int i = 0, j = 0;    T tmp;    for (i = 0; i<num; i++) {for        (j = i; j<num; j + +) {            if (A[i] < a[j])            {                tmp = a[i];                A[i] = a[j];                A[J] = tmp;}}}}    Template<class t>void Printfarray (T *a, int num) {    cout << Endl;    for (int i = 0; i<num; i++)    {        cout << a[i] << "";    }} void Main () {    int a[10] = {1, 3, 4, 5, 2, 3,, 6, 3};    int num = sizeof (a)/sizeof (*A);    Sortarray<int> (A, num);    Printfarray<int> (A, num);    Char buf[] = "163addeadfdsafdsaf";    int len = strlen (BUF);    Sortarray<char> (buf, Len);    Printfarray<char> (buf, Len);    System ("Pause");}  

3. Function templates encounter function overloading

Function templates can be overloaded like normal functions the C + + compiler takes precedence over normal functions if the function template can produce a better match, then the selection template can be qualified by the syntax of the empty template argument list to match the compiler only through templates
The/*1 function template can be overloaded like a normal function 2 C + + compiler takes precedence over normal function 3 If a function template can produce a better match, then selecting Template 4 can pass the syntax of the empty template argument list to the compiler only through template matching *//* Function templates do not allow automatic type conversions ordinary functions can be automatically type converted/#include <iostream>using namespace Std;int Max (int a, int b) {    cout << int Max (int A, int b) "<< Endl;    Return a > B? A:B;} Template<typename t>t Max (t A, T b) {    cout << "T Max (t A, T b)" << Endl;    Return a > B? A:B;} Template<typename t>t Max (t A, T B, t C) {    cout << "T Max (t A, T B, t C)" << Endl;    Return Max (Max (A, B), c);} void Main () {    int a = 1;    int b = 2;    cout << Max (A, b) << Endl;    cout << max<> (A, b) << Endl;    cout << Max (3.0, 4.0) << Endl;    cout << Max (5.0, 6.0, 7.0) << Endl;    cout << Max (' a ', +) << Endl;    System ("pause");    return;}

4. Function Template Nature inquiry:

The compiler does not treat function templates as capable of handling any type of functioncompilers produce different functions from function templates through specific typesThe compiler compiles two times the function template compiles the template code itself at the point of Declaration and compiles the code after the substitution of the parameter where it is called.
#include "Cstdlib" using namespace std;/* function Templates-the compiler does not handle function templates to handle any type of function-the compiler produces different functions from a function template through a specific type-the compiler compiles the function template two times- Compile the template code itself at the point where it is called-compile the *///template code after the call, and tell the compiler that it starts the generic programming//typename tells the compiler that the type name is T compiler you see type T don't mess up the error .... T is type, type is parameterized just template<typename t>void swap2 (t &a, T &b) {    T t = A;    A = b;    b = t;} int main () {    int x = 1;    int y = 2;    The invocation mode of generic programming is divided into two types    //automatic type deduction call    swap2<int> (x, y);    printf ("\n%d,%d", x, y);    float x1 = 1.0;    float y1 = 2.0;    The specific class shows    the call swap2<float> (x1, y1);    printf ("\n%f,%f", X1, y1);    cout << "Hello ...." << Endl;    System ("pause");    

The g++-s 1.cpp generates 1.S
Analysis 1.s
. File "1.cpp". Lcomm __zstl8__ioinit, 1, 1.def ___main;. SCL 2;. Type 32;. Endef.section.rdata, "Dr" Lc2:.ascii "hello....\0" LC3:. ASCII "Pause\0". Text. Globl _main. def _main;. SCL 2;. Type 32;.    Endef_main:p USHL%ebpmovl%esp,%ebpandl $-+,%espsubl $32,%espcall ___MAINMOVL $ (%ESP) MOVL $ (%ESP) Leal (%ESP),%eaxmovl%eax, 4 (%ESP) Leal (%ESP),%eaxmovl%eax, (%ESP) Call __z5swap2iievrt_ S1_//24-49movl $0x3f800000,%eaxmovl%eax, (%ESP) movl $0x40000000,%eaxmovl%eax, (%ESP) Leal (%ESP) ,%eaxmovl%eax, 4 (%ESP) Leal (%ESP),%eaxmovl%eax, (%ESP) call __z5swap2ifevrt_s1_//33-69movl $LC 2, 4 (%e SP) Movl $__zst4cout, (%ESP) call __zstlsist11char_traitsiceerst13basic_ostreamict_es5_pkcmovl $__ZSt4endlIcSt11cha    R_traitsiceerst13basic_ostreamit_t0_es6_, 4 (%ESP) Movl%eax, (%ESP) call __znsolsepfrsos_emovl $LC 3, (%ESP) call _SYSTEMMOVL,%eaxleaveret.section.teXt$_z5swap2iievrt_s1_, "x". Linkonce discard.globl __z5swap2iievrt_s1_.def __z5swap2iievrt_s1_;. SCL 2;. Type 32;. Endef__z5swap2iievrt_s1_:p USHL%ebpmovl%esp,%ebpsubl $16,%ESPMOVL 8 (%EBP),%EAXMOVL (%eax),%EAXMOVL%ea X, -4 (%EBP) movl (%EBP),%EAXMOVL (%EAX),%EDXMOVL 8 (%EBP),%eaxmovl%edx, (%eax) MOVL (%EBP),%eaxmovl-4 (% EBP),%edxmovl%edx, (%eax) leaveret.section.text$_z5swap2ifevrt_s1_, "X". Linkonce discard.globl __z5swap2ifevrt_s1_. def __z5swap2ifevrt_s1_;. SCL 2;. Type 32;. Endef__z5swap2ifevrt_s1_:p USHL%ebpmovl%esp,%ebpsubl $16,%ESPMOVL 8 (%EBP),%EAXMOVL (%eax),%EAXMOVL%ea X, -4 (%EBP) movl (%EBP),%EAXMOVL (%EAX),%EDXMOVL 8 (%EBP),%eaxmovl%edx, (%eax) MOVL (%EBP),%eaxmovl-4 (% EBP),%edxmovl%edx, (%eax) leaveret.text.def ___tcf_0;. SCL 3;. Type 32;. Endef___tcf_0:p USHL%ebpmovl%esp,%ebpsubl $24,%espmovl $__zstl8__ioinit, (%ESP) Call __znst8ios_base4ini Td1evleavereT.def __z41__static_initialization_and_destruction_0ii;. SCL 3;. Type 32;. ENDEF__Z41__STATIC_INITIALIZATION_AND_DESTRUCTION_0II:p USHL%ebpmovl%esp,%ebpsubl $24,%espcmpl $8 (%EBP) Jne L5cmpl $65535, (%EBP) jne l5movl $__zstl8__ioinit, (%ESP) call __znst8ios_base4initc1evmovl $___tcf_ 0, (%ESP) call _atexitl5:leaveret.def __global__sub_i_main;. SCL 3;. Type 32;.    Endef__global__sub_i_main:p USHL%ebpmovl%esp,%ebpsubl $24,%espmovl $65535, 4 (%ESP) MOVL $, (%ESP) call    __z41__static_initialization_and_destruction_0iileaveret.section.ctors, "W". Align 4.long __global__sub_i_main.def __zst4endlicst11char_traitsiceerst13basic_ostreamit_t0_es6_;. SCL 2;. Type 32;. Endef.def __ZSTLSIST11CHAR_TRAITSICEERST13BASIC_OSTREAMICT_ES5_PKC;. SCL 2;. Type 32;. Endef.def __znsolsepfrsos_e;. SCL 2;. Type 32;. Endef.def _system;. SCL 2;. Type 32;. Endef.def __znst8ios_base4initd1ev;. SCL 2;. Type 32;. Endef.def __znst8ios_base4initc1ev;. SCL 2;. Type 32;. Endef.def _atexit;. SCL 2;. Type 32;.  Endef

5.Class Template Basics

#include <iostream>using namespace std;//define a class template Template<typename T>class Aa{public:aa (T a) {this->a = a ;} void SetA (T a) {this->a = A;} T Geta () {return this->a}protected:private:t A;}; Class Bb:public aa<int>{public://bb (int a, int b): AA (a) BB (int a, int b): aa<int> (a) {this->b = b;} Private:int b;}; void Main () {//To define a class template as a type before defining the variable AA <int> a (10); BB B1 (1, 2); System ("Pause");}

6. Class template meets friend function

#include <iostream>using namespace Std;template<class t>class Complex{public:complex (t r = 0, t i = 0);  Complex (T a) {Real = A; Image = 0; }void print () const;//directly within the class declaration definition, otherwise the compiler alarms friend complex<t>operator+ (COMPLEX&LT;T&GT;&AMP;C1, complex<t &GT;&AMP;C2) {T r = C1. Real + c2.     Real; T i = c1. Image + c2. Image;return complex<t> (R, i);}  Friend Complex operator-(const complex<t> & C1, const complex<t> & C2);//friend Complex operator- (const complex<t> & c);p rivate:t Real, Image;};  Template<class T>complex<t>::complex (t R, t i) {Real = R; Image = i;} /* "Class complex<int> __cdecl operator+ (class complex<int> &,class complex<int> &)" ([email& NBSP;PROTECTED][EMAIL&NBSP;PROTECTED]@@[EMAIL&NBSP;PROTECTED]@Z), the symbol is referenced in the function _main 1>e:\01-work\09-employment class 0415\ day16\ generic programming \debug\ generic programming. Exe:fatal error lnk1120:1 an unresolved external command ========== build: 0 Successful, 1 failed, latest 0, skip 0 ==========*///tem Plate<class t>//Complex<t>operator+ (COMPLEX&LT;T&GT;&AMP;C1,COMPLEX&LT;T&GT;&AMP;C2)//{//T R = C1. Real + c2.     Real; T i = c1. Image+c2. Image;//Return complex<t> (R, I);//}template<typename t>void complex<t>::p rint () const{cout <&lt ; ' (' << Real <<, ' << Image << ') ' << Endl;} void Main () {COMPLEX&LT;INT&GT;C1 (1, 2); COMPLEX&LT;INT&GT;C2 (3, 4); COMPLEX&LT;INT&GT;C3 = C1 + c2;c3.print (); System ("Pause");}

7.class template meets static

#include "iostream" using namespace std;const double pi = 3.14159;template<typename t>class circle{t radius;static I The static data member of the NT total;//class template public:circle (T r = 0) {radius = R; total++;} void Set_radius (T r) {Radius = R;} Double Get_radius () {return Radius;} Double Get_girth () {return 2 * pi * RADIUS;} Double Get_area () {return pi * radius * RADIUS;} static int showtotal (); \//class template};template<typename t>int circle<t>::total = 0;template<typename T >int Circle<t>::showtotal () {return total;} void Main () {circle<int> A, b;//established 2 objects A.set_radius (+); cout << "A.radius =" << A.get_radius () < < Endl;cout << "A.girth =" << A.get_girth () << endl;cout << "A.area =" << A.get_area () << Endl; B.set_radius cout << "B.radius =" << B.get_radius () << endl;cout << "b.girth=" << b.ge T_girth () << endl;cout << "B.area =" << b.get_area () << enDl;cout << "total1=" << circle<int>::showtotal () << endl;//shows the number of objects established cout << Endl; Circle<double> X (6.23), Y (10.5), Z (25.6);//3 objects created cout << "X.radius =" << X.get_radius () << Endl ; cout << "X.girth =" << X.get_girth () << endl;cout << "X.area =" << X.get_area () << Endl;cout << "Y.radius =" << Y.get_radius () << endl;cout << "y.girth=" << Y.get_girth () &lt ;< endl;cout << "Y.area =" << y.get_area () << endl;cout << "z.girth=" << Z.get_girth () & lt;< endl;cout << "Z.area =" << z.get_area () << endl;cout << "total2=" << Circle<doub Le>::showtotal () << endl;//shows the number of objects established by system ("pause");




(11) Generic Programming/Function Templates/class 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.