Learning C ++ templates from scratch (1): function templates, function template specialization, overload function templates, and non-template function Overloading

Source: Internet
Author: User

I. Introduction

Consider the two functions max (A, B)
Different types of A and B have the same processing format:

Return a <B? B:;

Use existing methods to solve the problem:
(1) macro replacement # define max (A, B) (a) <(B )? (B): ())

Existing problems: Avoid type check

(2) Heavy Load

Problems: Many overloaded versions are required.

(3) Use function templates


Ii. Template

A template is a parameterized polymorphism tool.
Parameterization polymorphism refers to parameterization of the type of objects processed by a program, so that a piece of program code can be used to process multiple different types of objects.
With template programming, you can provide a code sharing mechanism for programs with the same logic and different data types.

Templates include function templates and class templates ). This article mainly discusses function templates.


Iii. function templates

(1) Use of function templates

Function templates are generally described as follows:

Template <template parameter table>

Return Value Type Function Name (template function parameter table ){

// Function Definition body

}

1. Function template definition starts with the keyword Template
2. List of parameters of the function template <> after the Template
3. the parameter of the function template is a type parameter and its type is class or typename.

Template <class T>

Template <class T1, class T2>


4. The template parameters are used as a type in the template. They can be used for function parameters, function return values, and function local variables.
5. Each template parameter must appear at least once in the function parameter list.

6. The scope of the template parameter name is limited to the scope of the function template.


(2) Use of function templates

1. The function template provides a unique function code for all functions, enhancing the versatility of function design.
2. To use a function template, describe the function template first, and then convert the Template into a corresponding template function for calling and execution.

The function template is not a function and cannot be executed.

Replace the type parameter in the code to get the template function -- instantiate

The instantiated template function is a real function and can be executed.

3. The template has been compiled twice.

Before instantiation, check the template code to check whether the syntax is correct. Here, you will find a syntax error, if a semicolon is missing.
During the instantiation, check the template code to see if all calls are valid. Invalid calls will be found here, for example, the instantiation type does not support some function calls or operators.

4. normal functions can be compiled smoothly only by declaring them. For template compilation, You need to view the template definition (the Declaration and definition must be placed in the same. h file)


(3) function template Specialization

Suppose we now have a template function max:

Template <typename T>
Const T & MAX (const T & A, const T & B)
{

Return a <B? B:;

}

Now we need to compare the size of two strings, for example:

Const char * str1 = "AAA ";
Const char * str2 = "Zzz ";

In this case, if the values of str1 and str2 are compared, that is, the pointer value is compared, rather than the string size. Therefore, we need to implement a special template function, as shown below:

Template <>
Const char * const & MAX (const char * const & A, const char * const & B)
{

Return strcmp (a, B) <0? B:;

}


(4) overload function templates, non-template function Overloading

The C ++ language can overload a function template.
You can use non-template functions to reload a function template with the same name.


Max. h:

C ++ code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# Ifndef _ max_h _
# DEFINE _ max_h _

# Include <iostream>
Using namespace STD;

Template <typename T>
Const T & MAX (const T & A, const T & B)
{
Cout <"template max (const T & A, const T & B)" <Endl;
Return a <B? B:;
}

// Function template overload
Template <typename T>
Const T & MAX (const T & A, const T & B, const T & C)
{
Cout <"template max (const T & A, const T & B, const T & C)" <Endl;
Return: max (a, B) <C? C: max (A, B );
//: Max calls non-template functions.
}

// Overload non-template Functions
Const Int & MAX (const Int & A, const Int & B)
{
Cout <"max (const Int & A, const Int & B)" <Endl;
Return a <B? B:;
}

// Special function Template
Template <>
Const char * const & MAX (const char * const & A, const char * const & B)
{
Cout <"template <> MAX (const char * const & A, const char * const & B)" <Endl;
Return strcmp (a, B) <0? B:;
}

// Overload non-template Functions
Const char * const & MAX (const char * const & A, const char * const & B)
{
Cout <"max (const char * const & A, const char * const & B)" <Endl;
Return strcmp (a, B) <0? B:;
}

# Endif // _ max_h _

Main. cpp:

C ++ code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# Include <iostream>
# Include <string>
Using namespace STD;

# Include "Max. H"

Class Test
{
Public:

Friend bool operator <(const Test & T1, const Test & T2)
{
Cout <"operator <(const Test & T1, const Test & T2)" <Endl;
Return true;
}
};

Int main (void)
{
// Different from STD: Max
Cout <: max (5.5, 6.6) <Endl; // automatically derive max (const double &, const double &);
Cout <: max ('A', 'C') <Endl; // automatically derives max (const char &, const char &);

Test T1;
Test T2;
: Max (T1, T2); // test: Operator <(const Test & T1, const Test & T2)

Const char * str1 = "AAA ";
Const char * str2 = "Zzz ";
Cout <: max (str1, str2) <Endl; // select a non-template function first.

Cout <: max <> (str1, str2) <Endl; // specify the template to use, and then find the template Specialization
// Cout <: max <const char *> (str1, str2); // explicitly specify the template special function max (const char * const &, const char * const & B)
Cout <: max (1, 5, 3) <Endl; // template matching for automatic Derivation

Cout <: max ('A', 50) <Endl; // 'A' is 97; select a non-template function (char can be implicitly converted to int)

Cout <: max (97,100) <Endl; // preferentially selects non-template Functions

Cout <: max <> (97,100) <Endl; // specify the template to automatically derive
// Cout <: max <> ('A', 50) <Endl; // error, specifying the template, but the compiler does not know how to derive
Cout <: max <int> (97,100) <Endl; // explicitly specify the template function max (const Int &, const Int &)
Cout <: max <int> ('A', 50) <Endl; // explicitly specify the template function max (const Int &, const Int &)

Return 0;
}


Function templates can be automatically deduced by passing parameter types to check whether appropriate function instances are available. Class templates must explicitly describe the type parameters of the template so that the template class can be instantiated.

Example.

Refer:

C ++ primer version 4
Valid tive C ++ 3rd
C ++ programming specifications

Related Article

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.