C + + Template Learning Essays

Source: Internet
Author: User

The content of this article is referenced in: http://www.cnblogs.com/gw811/archive/2012/10/25/2738929.html

C + + templates

1. Templates are divided into function templates and class templates two types

function templates for functions with different parameter types ;

Class templates have different classes for data members and member function types ;

The purpose of using templates is to allow programmers to write type-independent code . For example, to write a swap function that swaps two int types, this function can only implement the int type, the type of double, the characters cannot be implemented, and to implement these types of exchanges, we need to rewrite another swap function. The purpose of using a template is to make the implementation of the program independent of the type, such as a swap template function, that can achieve the int type, but also can achieve a double type of exchange.

Note: the declaration or definition of a template can only be done within a global, namespace, or class scope. That cannot be done within a local scope, such as a template cannot be declared or defined in the main function;

2. The general format of the function template is as follows:

Template <classclass return type   function name (argument list) {     function body}

where template and class are keywords, the class here can also be replaced with the typename keyword. The parameter in <> is called a template parameter, and template parameters cannot be empty . Once a template function is declared, you can declare a member of the function with the formal parameter name of the template function, that is, the template parameter name can be used wherever the built-in type is used in the function. When a template function is called, the template parameter is initialized by the argument of the template function, and once the compiler determines the actual template argument type, it is called an instance of the function template. The following is an example of the Swap template function:

Template <classvoid swap (t& A, t& b) {};

When such a template function is called, the type T is replaced by the type at which it is called. For example, swap (A, b), when a and b are int, the formal parameter T in the swap of the template function is substituted by int, and the template function becomes swap (int& a, int& b). When a and B in swap (A, b) are of type double, the template function changes to swap (double& A, double& b) accordingly. This also enables the code to be independent of type.

Demo: A template function that asks for the maximum value of two numbers

#include <iostream>using namespacestd;template<typename t>Constt& Max (Constt& A,Constt&b) {    returna > B?a:b;}intMain () {cout<<Max (2.1, 3.3)<< Endl;//template arguments are implicitly inferred as double typescout <<max<double> (2.1, 3.3)<< Endl;//Displays the specified argument type as doublecout <<max<int> (2.1, 3.3)<< Endl;//Displays the specified argument type as intSystem"Pause"); return 0;}

Result

3. The common format for class templates is as follows:

Template < class class name {    ...};..};

Class 3.1 Templates and function templates are made up of template parameter lists, template parameters cannot be empty , but class templates can be used to name member variables and member functions in the class template. That is, where you can use built-in types in your class, you can declare them using template parameter names.

Template <class t>class  demo{T A;  Public  : Demo (T first); T GetValue ();};

The member functions of the class 3.2 template are defined as follows (you need to add template<class t>before the implementation of each method):

Template <class t>Demo<T>::D Emo (T first) {    a=<class t>T Demo<T>:: GetValue () {    return  A;}

4. Template specialization (templates specialization) (Learn content reference http://blog.csdn.net/fingding/article/details/32079289 here)

4.1 The specialization of a template is that when the pattern in the template has a certain type, the template has a specific implementation. For example, suppose our class template pair contains a function that takes a modulo calculation (module operation), and we want this function to work only if the data stored in the object is integer (int), other times we need this function to always return 0. This can be done using the following code:

#include <iostream>using namespacestd;template<classT>classPair {T value1; T value2; Public: Pair (t first, T second) {value1=First ; value2=second; } T Module () {return 0; }}; Template<>classpair<int>{    intvalue1; intvalue2; Public: Pair (intFirstintsecond) {value1=First ; value2=second; }    intModule ();};
Template<>//Here is normally required, but the results compiled in VS2015 are as follows result11intpair<int>:: Module () {returnvalue1%value2;}intMain () {Pair<int> P1 (8,3); Pair<float> P2 (5.5,2.3); cout<< P1. Module () <<Endl; cout<< P2. Module () <<Endl; System ("Pause"); return 0;}

RESULT11:

1>------Started Build: Project: Template Specialization, configuration: Debug Win32------1>TemplateMain.cpp1>c:\users\administrator\documents\visual Studio -\projects\suanfa\shiyan1\test1--sequence\template Specialization\templatemain.cpp ( -):error C2910: "Pair<int>::module": cannot be explicitly specialized1>c:\users\administrator\documents\visual Studio -\projects\suanfa\shiyan1\test1--sequence\template Specialization\templatemain.cpp ( -): Warning C4305: "Parameters": from "DoubleTofloatthe Truncate========== Generation: Success0One, failure1A, Latest0One, skip0A ==========

Errors above: ErrorC2910 hint cannot display specialization, query C2910 error code, Solution: Remove function Module () before the template<> can be implemented;

There are a lot of links to learn about building and error handling: https://msdn.microsoft.com/zh-cn/library/z7kx322x.aspx

The result of the modified operation is as follows:

5. Examples of non-type parameters (ref.: http://www.cnblogs.com/gw811/archive/2012/10/25/2738929.html)

This example enables the user to specify the size of the stack in person and to implement the related operations of the stack

TemplateDemo.h

#pragmaOnceTemplate<classTintMaxsize>classStack {//maxsize Self-setting when creating objects by userPrivate: T elements[maxsize]; //An array containing the elements in the stack    intnumelements;//the number of elements in the current stack Public: Stack (); //constructor Function    voidPush (TConst&);//Press in Element    voidPop ();//Popup ElementsT Top ()Const;//returns the top element of the stack    BOOLEmpty ()Const{//determine if the stack is empty        returnNumelements = =0; }    BOOLFull ()Const{//determine if the stack is full        returnNumelements = =MAXSIZE; }};template<classTintMaxsize>Stack<t, Maxsize>::stack (): Numelements (0) {//initial stack does not contain any elements}template<classTintMaxsize>voidStack<t, Maxsize>::p Ush (TConst&elem) {    if(Numelements = =MAXSIZE) {        ThrowStd::out_of_range ("stack<>::p ush (): Stack if fulll"); } Elements[numelements]= Elem;//Adding a new element elem to the stack++numelements;//the number of elements in the current stack plus 1}template<classTintMaxsize>voidStack<t, maxsize>::p op () {if(Numelements <=0)    {        ThrowStd::out_of_range ("Stack<>::p op (), Stack is Empty"); }    --numelements;//reduce the number of elements}template<classTintMaxsize>T Stack<t, Maxsize>::top ()Const{    if(Numelements <=0)    {        ThrowStd::out_of_range ("Stack<>::p op (), Stack is Empty"); }    returnElements[numelements-1];//returns an element at the end (top of the stack)}

TemplateDemo.cpp

#include <iostream>#include<string>#include"TemplateDemo.h"using namespacestd;intMain () {Try{Stack<int, -> int20stack;//stacks that can store 20 data of type intstack<int, +> int40stack;//stacks that can store 40 data of type intstack<string, +> string40stack;//stacks that can store 40 data of type string//use a stack that stores 20 data of type intInt20stack.push (7); cout<< int20stack.top () <<Endl;        Int20stack.pop (); //use a stack that can store 40 data of type stringString40stack.push ("Hello"); cout<< string40stack.top () <<Endl;        String40stack.pop ();        String40stack.pop (); System ("Pause"); return 0; }    Catch(Conststd::exception&ex) {Cerr<<"Exception:"<< ex.what () <<Endl; System ("Pause"); returnExit_failure;//exit program with Error flag    }}

Result

C + + Template Learning Essays

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.