C ++ getting started with the template (1)-basic concepts and syntax of the template, basic syntax of the Getting Started tutorial

Source: Internet
Author: User
Tags float max

C ++ getting started with the template (1)-basic concepts and syntax of the template, basic syntax of the Getting Started tutorial
Reprinted please keep the following statement
Author: Zhao zongsheng
Source: http://www.cnblogs.com/zhao-zongsheng/preface

Some people may subconsciously feel terrible when talking about the C ++ template. In fact, the template is not complex and can be used in daily work. It can help us reuse the code and make the code simpler, easier to read, and more maintainable. We hope that this series of articles will allow more people to discover the charm of templates and help everyone write higher quality code.

Why do we need a template?

We sometimes encounter this situation: For the same function, we need to write different versions for different types. The content and logic are the same, but their types are different. For example, if we write a max function, input two numbers and return a large number. Naturally, the types of the two parameters must be the same as those returned. If you do not use a template, you need to use function overloading to write different functions for different types:

int max(int a, int b){     return a < b ? b : a;}float max(float a, float b){     return a < b ? b : a;}

Here I only wrote two functions. In fact, short, long, unsigned, double, and Other types all need special max functions. The result is that we need to write a dozen or so identical codes. If function functions are more complex and function implementation requires more lines, a large number of redundant and repetitive code may occur, which is not easy to maintain and prone to errors. In this case, it is much easier to generate a series of code in batches based on a specific template. Therefore, we can use the template in C ++

What is a template?

As the name suggests, a template is a model used by the compiler to generate code. There are two types of templates: function templates and class templates (variable templates started to appear in C ++ 14, but are not discussed here ). If you want to generate the function code, you need to use the function template. If you want to generate the class definition, you need to use the class template. This article will first introduce the function template, and the next article will introduce the class template.

Function Template

We can write a function template for the above series of max functions.

template<typename T>T max(T a, T b){     return a < b ? b : a;}

We will not elaborate on the syntax for the moment. Let's take a look at the rough look. In fact, the function template looks like a common function.

Now, we have defined a function template. How can we generate the function code? In fact, we don't need to do anything else. If we use the max function, the compiler will automatically generate the corresponding type of code for us. The function template is easy to use. You only need to write a pair of angle brackets after the Template Name, and then write the real parameter list in the angle brackets.

double d = max<double>(1.2, 2.4);

When the compiler sees this line, it will automatically generate the max function of the double version. The generated function is equivalent to replacing all T in the function template with double. Here, max <double> can be regarded as the function name of the max function of the double version. We can even use & max <double> to obtain the address of this function.

Let's look at a more complex example.

template<typename T, int i>T create(){    T value();    return value + i;}int main(){    float f1 = create<float, 1>();    // f1 == 1.0    float f2 = create<float, 2>();    // f2 == 2.0}

In this example, we define a create FUNCTION template. Two functions, create <float, 1> and create <float, 2>, are created and used according to the template. Note that these two functions are different and have different function bodies and different function addresses. The two of them are equivalent

float create()    // create<float, 1>{    float value();    return value + 1;}float create()    // create<float, 2>{    float value();    return value + 2;}

Let's summarize the syntax of the function template. The template definition starts with the template keyword, followed by a pair of angle brackets, which areList of template parametersThat is, the template parameters. The Writing Method of the template parameter list is similar to that of the function parameter list. All are in the form of "type parameter name, type parameter name. In the preceding example, the template parameter list is "typename T, int I ". We noticed that the template parameter list needs to specify a type for each parameter because the parameter is not necessarily of the C ++ type, but also a specific value, such as a number or pointer. If the parameter is a type, you need to use the typename keyword to represent the type of the parameter. If the parameter is a value, you need to write the type of the value. When using a template, add a pair of angle brackets after the Template Name.Template real parameter listIn the preceding example, the real parameters are "float, 1" and "float, 2 ". Similar to function calling, when using a template, the compiler checks whether the type of the real parameter list matches the type of the form parameter list. If the type does not match, an error is returned.

Advantages of using function templates

We can see from the above example that using function templates is more convenient and concise, and similar overload functions do not need to be repeatedly written. Besides, because the function code is generated when it is used, if we do not use this function, the compiler will not generate this code, so that we can reduce the program size. For example, if we use max <double> but not max <int>, there is only the max <double> function in the program, and there is no max <int> function.

 

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.