C ++ Primer study note _ 86 _ templates and generic programming

Source: Internet
Author: User
Tags define function

Templates and generic programming-heavy load and function templates

Introduction:

Function templates can be overloaded: You can define multiple function templates with the same name but different parameter numbers or types, or define common non-template functions with the same name as the function template.

However, declare a set of overload function templatesThey cannot be called successfully., The overloaded function template may cause ambiguity.



I. function matching and function Template

If there are both common functions and function templates in the overload function, the procedure for determining the function call is as follows:

1. Create a set of candidate functions for this function name, including:

A. Any common function with the same name as the called function.

B. Any function template is instantiated. In this example, the real parameters of the template are inferred and the functions used in the call are found.Template parameters that match real parameters.

2. Determine which common functions are feasible (if any ). Each template instance in the candidate set is feasible becauseReal parameter inference of the template ensures that the function can be called.

3. If a conversion is required for calling,Arrange reliable functions based on the type of conversion, Remember,The conversions allowed by calling the template function instance are limited..

A. If only one function is available, call this function.

B. If the call has ambiguity, remove all function template instances from the viable function set.

4. Rearrange the feasible functions of the function template instance.

A. If only one function is available, call this function.

B. Otherwise, the call is meaningless.



2. Example of function template matching

template <typename T>int compare(const T &,const T &);template <class U,class V>int compare(U,U,V);int compare(const char *,const char *);

The overload set contains three functions: the first template processes simple values, the second template compares the elements of two sequences, and the third is a common function that processes C-style strings.



3. Determine the call of the overload function Template

You can call these functions on different types:

    compare(1,0);    vector<int> ivec1(10),ivec2(20);    compare(ivec1.begin(),ivec1.end(),ivec2.begin());    int ia1[] = {0,1,2,3,4,5,6,7,8,9};    compare(ia1,ia1 + 10,ivec1.begin());    const char const_arr1[] = "world",const_arr2[] = "hi";    compare(const_arr1,const_arr2);    char ch_arr1[] = "world",ch_arr2[] = "hi";    compare(ch_arr1,ch_arr2);

Compare (1, 0 ):

Both parameters are of the int type. The candidate function is the first template to bind T to an int instance and a common function named compare. However, this normal function is not feasible-you cannot pass the int object to the expected char * object. The function instantiated with int exactly matches the call, so select it.


Compare (ivec1.begin (), ivec1.end (), ivec2.begin ()):

Compare (ia1, ia1 + 10, ivec1.begin ()):

Among the two calls, the only feasible function is the instantiation of the template with three parameters. Neither of the templates with two parameters nor the generic non-template functions can match the two calls.


Compare (const_arr1, const_arr2:

As we expected, this call calls a common function. This function is feasible and completely matched with the first template that binds T to constchar. According to rule (3) B, a common function is selected.Remove template instances from candidate setsOnly common functions are supported.


Compare (ch_arr1, ch_arr2 ):

This call is also bound to a common function. Candidates are the version of the function template that binds T to char *, and common functions that accept the constchar * real parameters,Both functions require a slight conversion to convert the ArrayCh_arr1AndCh_arr2Convert to pointer. Because the two functions match the same, normal functions take precedence over the template version.



Iv. Conversion and overloading of function templates

Design a set of overload functions, some of which are templates and others are common functions, which may be difficult. To do this, you need to have a deep understanding of the relationship between types. Specifically, when designing a template, implicit conversions that may or cannot occur. For example:

    char *ch_arr1 = "world",*ch_arr2 = "hi";    compare(ch_arr1,ch_arr2);

This call template version matches! In general, we want to obtain the same function whether it is to pass an array or to pass a pointer to the array element. However, in this example, the char * is bound toThe function template exactly matches the call.. The normal version still needs to be from char * To constchar *ConversionTherefore, the function template is preferred.

Another amazing change is that if the compare template version has a T-type parameter instead of the const reference of T, the following will happen:

template <typename T>int compare(T,T);

If there is an ordinary type array, the template version will be called whether the array itself is passed or the pointer is passed. The only way to call a non-template version isReal parameter isConstcharOrConstchar *When the pointer array is used:

// Call compare (T, T) char ch_arr1 [] = "world", ch_arr2 [] = "hi"; compare (ch_arr1, ch_arr2 ); char * p1 = "world", * p2 = "hi"; compare (p1, p2); // call compare (const char *, const char *) const char const_arr1 [] = "world", const_arr2 [] = "hi"; compare (const_arr1, const_arr2); const char * cp1 = const_arr1, * cp2 = const_arr2; compare (cp1, cp2 );

In these cases,Normal Functions and function templates exactly match. When the matching is the same, non-template versions are preferred.

[Best practices]

It is difficult to design a set of overloaded functions that contain both function templates and non-template functions, because it may make the function users feel strange,

Therefore:Define function template SpecializationAlmost always better than using a non-template version!


// P573 exercise 16.61/62 template <class U, class V> int compare (U, U, V) {cout <"U, U, V" <endl; return 0;} int compare (const char *, const char *) {cout <"cosnt char *" <endl; return 0 ;} template <typename T> int compare (T, T) {cout <"T, T" <endl; return 0;} int main () {char ch_arr1 [] = "world", ch_arr2 [] = "hi"; const char const_arr1 [] = "world", const_arr2 [] = "hi"; compare (ch_arr1, const_arr1); // const char * compare (ch_arr2, const_arr2); // const char * compare (0, 0); // T, T}

// Exercise 16.63 template <class T> T calc (T, T) {cout <"T, T" <endl;} double calc (double, double) {cout <"double, double" <endl ;}template <> char calc <char> (char, char) {cout <"char, char "<endl ;}int main () {int ival; double dval; float fd; calc (0, ival); // T, T calc (0.25, dval ); // double, double calc (0, fd); // double, double calc (0, 'J'); // double, double}

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.