Define templates-function templates and class templates

Source: Internet
Author: User

Both Object-Oriented Programming (OOP) and generic programming can handleUnknown type. The difference is:Oop can handle situations where the type is unknown before the program runs.AndIn generic programming, the type can be known during compilation..

The containers, iterators, and algorithms described above are examples of generic programming. When writing a generic program, code is written independently with any specific type. When using a generic program, we provide the type or value, and the program instance can run on it.

Templates are the basis of generic programming. A template is a blueprint or formula for creating classes or functions. When a generic type such as vector or find is used, we provide enough information to convert the blueprint to a specific type function. This type of conversion occurs during compilation.

Define Template

Suppose we want to write a function to compare two values and point out whether the first value is less than, equal to, or greater than the second value. In practice, we may want to define multiple functions. Each function compares a value of a given type. Our first attempt may define multiple overload functions:

int compare(const string &v1,const string &v2){    if(v1<v2) return -1;    if(v1>v2) return 1;    return 0;}int compare(const double &v1,const string &v2){    if(v1<v2) return -1;    if(v1>v2) return 1;    return 0;}

The two functions are almost the same. The only difference is the parameter type, and the function body is the same.

If you have to repeatedly define the same function body for each type you want to compare, It is very cumbersome and error-prone. What's more troublesome is that when writing a program, we need to determine all types that may need to be compare.

Function Template

We can define a general function template, instead of defining a new function for each type. A function template is a formula used to generate a function version for a specific type. The template version of compare may be as follows:

template<typename T>int compare(const T&v1,const T &v2){    if(v1<v2) return -1;    if(v1>v2) return 1;    return 0;}

The template definition starts with a keyword template, followed by a template parameter list. This is a comma-separated class Table for one or more template parameters, with a smaller than sign (<) and greater than sign (>) surrounded.

In the template definition, the template parameter list cannot be blank.

The template parameter list works much like the function parameter list. The function parameter list defines some specific types of local variables, but does not specify how to initialize them. During running, the caller provides real parameters to initialize the parameters.

Similarly, the template parameter indicates the type or value used in the class or function definition. When using a template, We (implicitly or explicitly) Specify the template arguments and bind them to the template parameters.

Our Compare function declares a type parameter named T. In compare, we use the name t to represent a type. The actual type T indicates is determined based on the usage of compare during compilation.

Instantiate a function Template

When we call a function template, the compiler (usually) uses the function arguments to infer the real parameters of the template. That is, when compare is called, the compiler uses the real parameter type to determine the type bound to the template parameter T. For example, in the following call:

Cout <compare () <Endl; // T is int

The real parameter type is int. The compiler will infer that the real parameter of the template is int and bind it to the template parameter T.

The compiler instantiates a function of a specific version for us using the inferred template parameters. When the compiler instantiates a template, it uses the actual template parameters instead of the corresponding template parameters to create a new "instance" of the template ".

For example, the following call is given:

// Calculate the int compare (const Int &, const Int &)

Cout <compare () <Endl; // T is int

// Instance the int compare (const vector <int> &, const vector <int> &)

Vector <int> vec1 (1, 2, 3), vec2 (4, 5, 6 );

Cout <compare (vec1, vec2) <Endl; // T is vector <int>

The compiler will generate two different versions of compare. For the first call, the compiler will compile and compile a compare version, where T is replaced with INT:

int compare(const int &v1,const int &v2){    if(v1<v2) return -1;    if(v1>v2) return 1;    return 0;}

For the second call, the compiler generates another compare version, where T is replaced with vector <int>. The versions generated by these compilers are generally called template instances.

Template type parameters

Our Compare function hasTemplate type parameters. Generally, we can regard type parameters as type specifiers, just like built-in type or class type specifiers.. In particular, type parameters can be used to specify the type of the response type or function, and in the function body for variable declaration or type conversion.

The type parameter must use the keyword class or typename:

// Error: class or typename must be added before u

Template <typename t, u> T calc (const T &, const U &);

In the template parameter list, the two keywords have the same meaning and can be converted to each other. These two keywords can be used in a template parameter list at the same time:

// Correct: in the template parameter list, typename and class are no different.

Template <typename T, Class U> calc (const T &, const U &);

It seems that using the keyword typename to specify template type parameters is more intuitive than using class. After all, we can use the built-in (non-class) type as the real parameter of the template type. In addition, typename clearly states that the subsequent name is a type name.

 

Non-type template parameters

In addition to defining type parameters, you can also define non-type parameters in the template definition. A non-type parameter indicates a value rather than a type. We specify a non-type parameter through a specific type name rather than the class or typename keyword.

When a template is instantiated, non-type parameters are replaced by values provided by a user or inferred by the compiler. These values must be constant expressions that allow the compiler to instantiate the template during compilation.

 

Define templates-function templates and class templates

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.