"C + + Standard Template Library Note 1" Template technology for C + + __c++

Source: Internet
Author: User
Tags function definition
/**************************************************************************************************************
file Description:
        C + + template technology
development environment:
        Win10+vs2013+stl Time and
place:
        Shaanxi Normal University Wen Jin Lou 2017.7.26    :
        September
************************************************************************************************** ***********************/
(i) Introduction to C + + template technology

1 C + + template is a very important technology, STL Standard Template Library of the general algorithm and container is achieved through the template programming, and to function templates and class templates provided.

2 as the name suggests, the role of the template is to customize functions and classes. As long as you pass data types to function templates and class templates, can generate a specific data type of functions and classes, the implementation of different data types, but the program logic exactly the same code reuse, reduce the workload of programming, and can make a lot of commonly used functional code complete and concise into the standard library, greatly improved the C + + into the environment.

3 template is simply to promote the preprocessing of the macro to C + +, unlike the macro with a set of "instruction at the beginning of the #, the end of the instruction does not apply to the semicolon, identifier definition does not apply the type" of the controversial syntax.

4 the definition of a template can be combined with the definition of functions and classes, it is entirely on their basis to add some new syntax, so also known as function templates and class templates, indicating that the syntax of the template is modeled on familiar functions and class syntax, but the data type needs to be declared as generics with the keyword templates. (b) function template (1) Concept of function template

Suppose you want to write a function that sums two parameters. In actual programming, we might want to define a few such functions, each of which can sum up a value of a given type, and then may naturally think of the overload of the function. For example:

int add (int a, int b)
{return
	a + b;
}
Double Add (double A, double b)
{return
	a + b;
}
Char Add (char A, char b)
{return
	a + b;
}
These functions are almost identical, the function bodies of each function are the same and functionally the same, and the only difference between them is the type of the formal parameter and the type of the function return value.

In fact, when we write the code, we have to write all the code by hand, so we use the copy, paste, and edit function to get another type of sum function. If each type requires a function body of a repeating function, it is not only troublesome, but also error prone. More importantly, you need to know in advance all types of combinations that might be supported. This approach is problematic if you want to use a function for an unknown type.

C + + has a template (template) mechanism, you can use the function template to solve the above problems. A function template (functional template) is a type-independent function that can be used as a pattern to produce a specific type version of a function.

Function templates allow you to design generic functions that are independent of the type and that are automatically instantiated only when needed to form a "batch type" programming approach. (2) definition and use of function templates (1) Definition of function template

The syntax for a function template definition is:

template< template formal parameter list > return value type function name (formal argument lists)
{
	function body
}
As you can agree, line 1th is called a template definition, which is then called a template function, similar to the function definition syntax.

The template definition starts with the keyword template, followed by the template parameter list. The template parameter list (template parameter list) is a list of one or more template parameters enclosed by a pair of angle brackets <>, and is not allowed to be empty, and the formal parameters are separated by commas, in the form of two:

The first form looks like this:
      typename type parameter name 1,typename type parameter name 2
..... The second form looks like this:
      class type parameter name 1,class type parameter Name 2 ..........		 
In the function template parameter list, TypeName and class have the same meaning, can be used interchangeably, or two keywords can be used in the same template parameter list.

However, because class keywords in C + + are often easy to associate with classes, the use of keyword TypeName is more intuitive than using class, TypeName can be more intuitive to reflect that the following name is a type name.

The template definition is followed by the function definition, in which you can use the type parameters in the template parameter list. For example:

Template<typename t> Add (t A, T B)
{return
    a + b;
}
The meaning of the function template definition syntax is a universal function, the function type and the formal parameter type are not specified, but a type notation indicates that the type notation is determined by the compiler based on the function used, and this universal function becomes the function template.
When you use a function template, the compiler infers that (or those) template arguments are bound to the template parameters, and once the compiler determines the actual template arguments, the function template is instantiated. That is, the compiler will determine what type replaces each type parameter, and what value replaces each untyped parameter, and after the actual template argument is deduced, the compiler uses the type arguments instead of the corresponding template parameters to produce and compile the version of the function. Here, the compiler undertakes the repetitive work we use for each type of writing, and we do not have to hand-write the machine for copying, pasting, modifying, etc.

(2) Use of function templates

You can use template function calls like normal functions.

#include <iostream>

using namespace std;

Template<typename t>t Add (t A, T B)
{return
	a + b;
}

int main ()
{
	std::cout << "Int_add    ="    << Add (10,20) << Std::endl;
	Std::cout << "Double_add ="    << Add (10.2, 20.5) << Std::endl;
	Std::cout << "Char_add   ="    << Add (a) << Std::endl;
	Std::system ("pause");
	return 0;
}

(iii) class template

(1) Introduction to class templates

Like a function template, a class template generalizes the data type of the data member and the parameter types of the member function. The following is a basic definition form of a class template, the keyword Template description type t1~tn is a template type, and member functions can be defined in the declaration of the class templates.

Template<class t1,class T2,....., class tn> class name
{
	//member declaration or definition;
};
Template<class T1, Class T2, ..., class tn> return value class name <t1,t2, ..., tn>:: member function 1
{
	//function definition
}
Template<class T1, Class T2, ..., class tn> return value class name <t1, T2, ...:: member function 2
{
	//function definition
}
Note:

Unlike non-template code organization, function templates and class template declarations and definition code, are generally written in the. h header file, so as not to be prompted to compile link errors due to the present.

Here is an example of a class template representing points on a plane:

Template<class t>                                   //"0" class template defines class point                                          //"1" point not the class name is the template name
{public
:
	point::x (0), Y (0) {}                             //"2" default constructor point
	(const t A, const T b):(X) (a), Y (b) {}    //"3" constructor
	void Set with parameters (const t A, const T b);
	void Display ();
Private:
	T x;
	T y;
};




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.