C ++ templates and generic programming (1) template definition-book notes in c ++ primer

Source: Internet
Author: User

C ++ templates and generic programming (I) template Definition
-- C ++ primer Reading Notes by Drizzle QQ: 253786989

Generic programming refers to writing code independent from specific types. c ++ STL is the ultimate use of generic programming. For example, vector is a generic container that can contain n elements of multiple types. In use, specify the element type: vector <int>
Vi; or vector <float> vf;

Templates are the foundation of generic programming. without the support of templates, generic programming cannot be discussed.

Function template (Function Template)

A function template is a type-independent special function. A function template can generate a function version for a specific type.

For example:

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


Compare can compare the numbers of two int types or two string types. From this we can see that templates and generic programming are powerful. If you do not use the template technology and want to compare int type, string type, and custom type, you need to write a function for these types, this increases the amount of code and is not easy to maintain.


<Typename T> it is called a template parameter table. T is a template parameter. Multiple Template parameters are separated by commas. The template parameter table cannot be blank.

Use of function templates

For example:

int main(){    cout << compare(3, 5) << endl;    string s1 = "hello", s2 = "world";    cout << compare(s1, s2) << endl;}

For "compare (3, 5)", the compiler will first infer that the type of the function parameter is int, and then bind the int to the template parameter T of compare. This process becomesInstantiation(Instantiate) an instance of the function template. In fact, the compiler helps programmers compile a compare for the int version.

Template parameter type

There are two types of template parameters:Type parameter(Type parameter ). The preceding "typename T" is a type parameter, because T represents a type. Another template parameter isNon-type parameters(Nontype
Parameter ).

For example:

template <typename T, size_t N>void array_init(T (&parm)[N]){    for (size_t i = 0; i != N; ++i)    {       parm[i] = i;    }}

"Size_t N" is a non-type parameter, because it does not represent a type. When array_init is called, the compiler calculates the value of the non-type parameter of the function template from the array arguments. For example:

int ia[10];array_init(ia);

Then the compiler binds the form parameter of the function template array_init to int [10], and instantiate an array_init version as follows: array_init (int
(&) [10]), that is, the value of N is 10.

The name of the template parameter cannot be reused within the template.

template <typename T>int compare(const T &lhs, const T &rhs){    typedef int T; //error    // …    return 0;}

This code will cause a compilation error because the template parameter T cannot be reused within the template.

Inline (Inline) Function Template

The function template can also be declared as inline in the following format (note the position of inline ):

template <typename T> inline int compare(const T &lhs, const T &rhs); 

Class template (Class Template)

The so-called class template means that this class can support different types of objects.

For example:

template <typename T>class Queue{public:    Queue();    T &front();    const T &front()const;    void push(const T &);    void pop();        bool empty() const;private:    // ...};

The definition of a class template is similar to that of a common class. The main difference is the type T, which allows Queue to instantiate different classes for different types. For example:

Queue<int> qi;Queue<string> qs;

It should be noted that the class template is just a template, and it is not a class, so: Queue q; will not be compiled, because Queue is not a type. The Queue <int> is a specific class instantiated based on the class template Queue. Therefore, you can define a variable qi of the Queue <int> type.

Specify the type within the template.

This sentence can be easily understood only by combining specific examples:

template <typename Parm, typename U>Parm fcn(Parm* array, U value){    Parm::size_type * p;    // ...}


Parm is a class. A class can have both data and function members and type members. For example, the STL container class has a type member: size_type. In the above function template, when the compiler Encounters "Parm: size_type", it does not know whether it is a data or a type, generally, the compiler assumes that such a name is a data, so "Parm: size_type
* P "is the multiplication of two data, which is certainly not the result we want. To let the compiler know that "Parm: size_type" is a type, add "typename" before it, as shown below:

template <typename Parm, typename U>Parm fcn(Parm* array, U value){    typename Parm::size_type * p;    // ...}

Compile generic programs

The following function template is used to compare two values of a certain type. The programmer must ensure that this type supports the "<" operator; otherwise, compilation errors may occur. For example, if a user-defined type does not have the "<" operator defined, the function template cannot be used.

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

When writing a generic program, the template parameters are usually referenced using const, so that the template can use a type that does not allow value assignment. In addition, the requirements for type T should be minimized when writing operations in the template. For example, if the preceding function is written as follows, the type T must support both the "<" and ">" operators.

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

C ++ templates and generic programming (I) template Definition
-- C ++ primer Reading Notes by Drizzle QQ: 253786989

 

 

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.