C ++ template. The complete guide Note 2 function templates

Source: Internet
Author: User

The pressure on macros (preprocessing) is too deep, so the first thing after the template is available is to define the template function to replace those Max and Min. The author is also happy with this. Next I will immediately look at the implementation of a simplest template function max:

Template <typename T> <br/> inline t const & MAX (T const & A, T const & B) <br/> {<br/> // If a <B then use B else use a <br/> return a <B? B: A; <br/>}

If you try to explain it one by one, it is like this: Template indicates that this is a template function. <> the template parameter area is specified, and typename indicates that the following parameter is a type name, t indicates a broad type, which can be used to specify all types (INT, float, STD: string ). All of these constitute the most basic template function. It must be noted that due to historical reasons, typename can be replaced by class. (Many of them are described using class ). Of course someone asked me if struct is okay. Of course the answer is no!

After understanding the definition of this function, the second step is to explore how to call it. Here are several examples:

<Br/> MAX (1, 2); // max <int> <br/> MAX ('1', '2 '); // max <char> <br/> MAX (1, 2.5); // compile error <br/> max <double> (1, 2.5 ); // max <double>

The first and second calls have no problems, just like common function calls. Of course, their calls can be successful. However, when the third call occurs, the compiler reports an error 'const T & MAX (const T &, const T &)': template parameter 't' is ambiguous. We can see that there is a problem with the parameter type here, and the two parameters have different types. The compiler does not know how to specify t because it is an int or a double. Note that the compiler requires an exact type, so it will not take the initiative to convert it to you. Not from int32 to int16. So here you need to explicitly tell the compiler how to do it. This is the fourth call.Max <double> (1, 2.5 );Or you can forcibly convert parameter 1 to double and then call it, for exampleMax (static_cast <double> 1, 2.5).

Furthermore, let's take a look at how the compiler helps us implement these calls. To put it simply, the compiler uses the method of calling what type exists, and I will generate a bunch of Max code corresponding to what type. For exampleMax (1, 2 );When the call comes, I will generate such code for you:

// Maximum of two int values <br/> inline int const & MAX (INT const & A, int const & B) <br/>{< br/> return a <B? B: A; <br/>}

It is to use int to replace the original t to generate specific types of code, so that the original programmer needs to write the function for different types of versions and then hand it over to the compiler. The process in which the compiler generates the corresponding function code for different types is called Instantiation. it is a coincidence that the instantiation in OO is the same word. Of course, the meaning is definitely different ). Next we can look at a complex example:

# Include "stdafx. H "<br/> # include <iostream> <br/> # include <cstring> <br/> # include <string> <br/> // maximum of two values any Type <br/> template <typename T> <br/> inline t const & MAX (T const &, t const & B) <br/>{< br/> return a <B? B:; <br/>}< br/> // maximum of two pointers <br/> template <typename T> <br/> inline T * const & MAX (T * const &, T * const & B) <br/>{< br/> return * A <* B? B: A; <br/>}< br/> // maximum of two C-strings <br/> inline char const * const & MAX (char const * const &, <br/> char const * const & B) <br/>{< br/> return STD: strcmp (a, B) <0? B: A; <br/>}< br/> int _ tmain (INT argc, _ tchar * argv []) <br/>{< br/> int A = 7; <br/> int B = 42; <br/>: max (A, B ); // max () for two values of Type int <br/> STD: String S = "hey"; <br/> STD: String T = "you "; <br/>: max (S, T); // max () for two values of Type STD: String <br/> int * P1 = & B; <br/> int * P2 = & A; <br/>: max (P1, P2); // max () for two pointers <br/> char const * S1 = "David"; <br/> char const * S2 = "Nico"; <br/>: max (S1, s2); // max () for two C-strings </P> <p> char * a1 = "Cy"; <br/> char * a2 = "hy "; <br/>: max (a1, a2); <br/> return 0; <br/>}

This is a complete example running under vs2005. The difference here is that the template function has different overloaded versions. Before instantiation, we need to find the most suitable function call for different types, such as calling Max (, b); When A and B are all int, the compiler finds that the first max function is the most matched version with value as the parameter, so the int version of the first function will be developed for this instance. Note that the matching process here is called deduction ). The basic principle of deduction is to first match non-template functions that coexist, and find the closest template function if they fail. For example, max (S1, S2); matches the max function of the version of const char *, while Max (a1, a2 ); is the second Max function, that is, the version of the type parameter as the pointer.

So far, it is still a bit of flowers and flowers. The smart compiler can do everything we want. Max's performance is surprisingly consistent with what we expected. Of course, one thing we have to mention is the surge of calm. See the following example:

# Include <iostream> <br/> # include <cstring> <br/> # include <string> <br/> // maximum of two values of any type (call- -Reference) <br/> template <typename T> <br/> inline t const & MAX (T const & A, T const & B) <br/>{< br/> return a <B? B: A; <br/>}< br/> // maximum of two C-strings (call-by-value) <br/> inline char const * max (char const * a, char const * B) <br/> {<br/> return STD: strcmp (A, B) <0? B: A; <br/>}< br/> // maximum of three values of any type (call-by-Reference) <br/> template <typename T> <br/> inline t const & MAX (T const & A, T const & B, T const & C) <br/> {<br/> return max (a, B), c); // error, if Max (A, B) uses call-by-value <br/>}< br/> int main () <br/>{< br/>: max (7, 42, 68 ); // OK <br/> const char * S1 = "Frederic"; <br/> const char * S2 = "Anica "; <br/> const char * S3 = "Lucas"; <br/>: max (S1, S2, S3); // error <br/>}

We can see that if these template parameter types do not match, the problem is great. We can see max (, 68); there is no problem, the max functions of the three parameters match the first max function. There is no problem here. We all use reference semantics. But to max (S1, S2, S3);, the max (a, B), c); matches the max version of const char *. In this way, the return value of Max is changed from reference to stack value. Although the comment here writes error, in fact, only one returning address of local variable or temporary warning will be reported in vs2005! Attention should be paid to the packages that take error as the condition for judgment. In fact, such warning will also be fatal. Therefore, smart compilers do not always give us peace of mind.

 

 

 

 

 

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.