C + + template Getting Started tutorial (i)--template concept and basic grammar

Source: Internet
Author: User
Tags class definition

Reprint Please keep the following statement
Zhaozong
Source: http://www.cnblogs.com/zhao-zongsheng/Preface

Some people refer to C + + templates that subconsciously feel horrible, ignorant, and distant. In fact, the template is not complex, and proficiency can be used in daily work, can help us to reuse code, so that the code is more concise, easy to read, maintainable. Hopefully this series of articles will allow more people to discover the charm of the template and help you write more high-quality code.

Why we need templates

We sometimes encounter this situation: the same function, we want to write for different types of different versions, the content and logic are the same, only their type is not the same. For example, we write a max function, passing in two digits, returning a large number. Naturally, the type of the two parameters and the returned type must be the same. If you do not use a template, we need to use function overloading to write different functions for different types:

int max (intint  b) {     return a < b b:a;} float Max (floatfloat  b) {     return a < b b:a;}

Here I only wrote 2 functions, in fact short, long, unsigned, double, and so on all need a special Max function, the result is to write more than 10 almost a touch of the same code. If the function is more complex, the function implementation needs more rows, there will be a lot of redundant duplicated code, and it is not easy to maintain, easy error. This time it would be much easier if we could generate a series of code in batches based on a specific template. To do this, we can use the templates in C + +

What is a template

As the name implies, a template is a mold used by the compiler to generate code. There are two types of templates, function templates and class templates (c++14 start with variable templates, but not discussed here). If you want to generate function code, you need a function template, and if you want to generate a class definition, you need to use a class template. This article introduces the function template first, and the next article introduces the class template.

function templates

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 do not elaborate on the grammar, first look at the general appearance, in fact, the function template looks and the normal function is very similar.

Well, we've defined a function template, so how do we generate the function code? In fact we don't need to do extra things, and if we use the Max function, the compiler will automatically help us generate the corresponding type of code. The function template is very simple to use, just write a pair of angle brackets behind the name of the template, and the list of arguments in the angle brackets can be used.

double d = max<double> (1.22.4);

When the compiler sees this line, it automatically generates a double version of the Max function, which is equivalent to replacing all the t in the function template with a double. Here max<double> can be seen as the function name of the double version of the Max function, and we can even use &max<double> to get the address of the function.

Let's look at a more complicated example.

int i>t Create () {    T value ();     return value + i;} int Main () {    float f1 = create<float1> ();    // F1 = = 1.0    float F2 = create<float2> ();    // F2 = = 2.0}

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

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

We summarize the syntax of the function template, which begins with the template keyword, followed by a pair of angle brackets, which are the template parameter list , which is the parameters of the template. The wording of the template parameter list and the function parameter list are very similar. Are "type parameter names, type parameter names, ..." in this form. In the example above, the template parameter list is "typename T, int i". We notice that the template parameter list needs to specify a type for each parameter, because the formal parameter is not necessarily a C + + type, or it can be a specific value, such as a number, a pointer, and so on. If the parameter is a type, you need to use the TypeName keyword to represent the type of the formal parameter, and 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's name, and a list of template arguments inside the angle brackets, in the example above, the argument list is "float, 1" and "float, 2". Similar to function calls, when using a template, the compiler checks that the type of the argument list matches the type of the parameter list, and the mismatch will cause an error.

Advantages of using Function templates

As we can see from the example above, it is more convenient and concise to use a function template, and it is not necessary to repeat similar overloaded functions. In addition, since the function code is generated when it is used, the compiler will not generate this code if we do not use this function, so we can reduce the size of the program. For example, we used Max<double>, but did not use MAX<INT>, then there is only max<double> function in the program, there is no max<int> function.

C + + template Getting Started tutorial (i)--template concept and basic grammar

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.