C + + templates

Source: Internet
Author: User

Template definition: A template is a tool for implementing the code reuse mechanism, which can implement type parameterization, that is, to define the type as a parameter, thus enabling real code reusability. Template can be divided into two categories, one is a function template, the other is a class template. function templates are for functions that differ only in parameter types, and class templates are for classes that differ only in data members and member function types.

Note: The declaration or definition of a template can only be done within a global, namespace, or class scope.

I. General formula of function template

1. Format of function Template:

Template <class parameter name, class parameter name,......> return type function name (argument list)

{

function body

}

Where template and class are related to the word, class can be used typename to see the word instead, here TypeName and class no difference,<> the parameters in parentheses are called template parameter, template parameter and function parameter is similar, template parameter cannot be empty. Once you declare a template function, you can use the formal parameters of the template function to name the member variables and member functions in the class, that is, the template parameter names can be used wherever the built-in type is used in the function. The template parameter requires the template arguments provided when the template function is called to initialize the template parameter, and once the compiler determines the actual template argument type, it is called an instance of the function template. For example, the form of swap template function is

Template <class t> void Swap (t& A, t& b) {},

When such a template function is called, the type T is replaced by the type of the call, such as swap (A, a, b) where a is the type int, and the parameter T in the swap of the template function is replaced by int, and the template function becomes swap (int &a, int &b). When swap (C,D) where C and D are double types, the template function is replaced with a swap (double &a, double &b), which implements the type-independent code that implements the function.

2, note: For the function template does not have a call of H (int,int), cannot specify the type of template parameter in the parameters of the function call, the call to the function template should use argument deduction, that is, only H (2,3) such a call, or int a, b; H (A, B).

#include <iostream>using namespacestd;/*function templates for different data types*/Template<classTclassT1,classT2>T Sub (T1 A, T2 b) {returnAb;}intMainvoid) {cout<<"8-1.5 ="<< sub<float,int,float> (8,1.5) <<Endl; return 0;}

Ii. class template General formula

1. The format of the class template is:

Template<class parameter name, class parameter name,...> class name

{ ... };

Both the class template and the function template are made up of template parameter lists starting with the template, which cannot be empty, but declaring a class template can be used to name the member variables and member functions in a class template, that is, a template parameter name can be used where a built-in type can be used in a class. Like what

Template<class t> class A{public:t A; T b; T Fun (t C, t &d);};

In Class A, two member variables A and B are declared with type T, and a function fun with a return type of T with two parameter type T is declared.

2, the creation of class template objects: For example, a template Class A, the use of the class template to create an object is a<int> m, followed by a <> angle bracket after class A and fill in the corresponding type, so that the general use of the template parameter in Class A will be replaced by Int. When a class template has two template parameters, the method for creating the object is A<int, double> m, and the types are separated by commas.

3. For a class template, the type of the template parameter must be explicitly specified in the angle brackets after the class name. such as a<2> m; it is wrong to set the template parameter to int in this way (Compile error: ' Error C2079: ' A ' uses undefined class ' a<int> '), and the class template parameter does not exist for argument deduction. In other words, the integer value 2 cannot be deduced to be passed to the template parameter as int type. To set the class template parameter to int type, you must specify a<int> m as such.

4. The method for defining member functions outside the class template is:

template< template parameter list > function return type class name < template parameter name;:: function name (argument list) {function Body},

For example, with two template parameter t1,t2 with a void H () function in Class A, the syntax for defining the function is:

Template<class t1,class t2> void A<t1,t2>::h () {}.

Note: When you define a member of a class outside of a class, the template parameters after the templates should match the template parameters of the class you are defining.

#include <iostream>using namespacestd;/*class template, external definition member function for class template*/Template<classT>classa{ Public: A (inti): x (i) {} T GetX ();Private: T x;}; Template<classT>T A<T>:: GetX () {returnx;}intMainvoid) {A<int> A (Ten); cout<< A.getx () <<Endl; return 0;}

Third, the formal parameters of the template

There are three types of template parameters: type parameters, non-type parameters, and template parameters.

1. The type parameter consists of the keyword class or typename followed by a specifier, such as template<class t> void H (t a) {}, where T is a type parameter, and the name of the type parameter is determined by the user.

2. The template parameter represents an unknown type. A template type parameter can be used as a type description trailing characters anywhere in the template, in exactly the same way as a built-in type specifier or class type specifier, that is, you can use to specify return types, variable declarations, and so on.

3. (For function templates) You cannot specify two different types for the same template type parameter, such as Template<class t>void H (t A, T b) {}, Statement invocation H (2, 3.2) error because the statement specifies two types for the same template parameter T. The first argument 2 designates the template parameter T as int, and the second argument 3.2 designates the template parameter as a double, and the two types of parameters do not match, and an error occurs.

4. (for class templates) when we declare that the class object is:a<int> A, such as Template<class t>t g (t A, T b) {}, the statement call A.G (2, 3.2) will compile without error, but there will be a warning, Because the T is converted to the int type when declaring the class object, and the second argument 3.2 specifies the template parameter as a double, at run time, 3.2 is cast to 3. When we declare that the object of the class is:a<double> A, there is no warning above, since int to double is an automatic type conversion.

5. Non-type template parameter: The template's non-type parameter is the built-in type parameter, such as Template<class T, int a> class b{}, where int A is a non-type template parameter.

6. A non-type parameter is a constant value inside the template definition, meaning that the non-type parameter is constant inside the template.

7. Non-type template parameters can only be integers, pointers and references, such as double,string, String * * Such types are not allowed. But Double &,double *, the object's reference or pointer is correct. An argument that calls a non-type template parameter must be a constant expression, such as: template <class T, int a> class A{};const int B, A<int, b> m, is correct, that is, he must be able to calculate the results at compile time.

8. Note: Any local object, local variable, local object address, local variable address is not a constant expression, and cannot be used as an argument for a non-type template parameter. Global pointer type, global variable, global object is not a constant expression, and cannot be used as an argument for a non-type template parameter. The address or reference of a global object a const type variable is a constant expression that can be used as an argument for a non-type template parameter. The result of a sizeof expression is a constant expression that can also be used as an argument to a non-type template parameter.

9. Allowable transformations between formal parameters and arguments of non-type template parameters: Allow conversion from array to pointer, from function to pointer, const modifier, boost conversion, integer value conversion, General conversion.

10. You can provide default values for the type parameters of a class template, but you cannot provide a default value for the type parameters of the function template. Both the function template and the class template can provide default values for the template's non-type parameters. The default value of the class template type parameter is the same as the default parameter of the function, and if more than one type parameter sets the default value for all template parameters after the default value is set from the first parameter, the template's formal parameter list should omit the default formal parameter type when a member of the class is defined outside the class template. such as: Template<class T1, Class t2=int> class a{}; Provides the default value of type int for the second template type parameter T2. Template<class T1=int, class T2>class a{}; it is wrong, because T1 gives default values, and T2 is not set.

C + + 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.