HLW's C + + learning Notes template and generic programming

Source: Internet
Author: User

function templates

Role

There are many times when the type of the parameter and the type of the return value is variable, and we define the template to make the function more flexible to use.

We design a comparison function, if we can compare the two parameters are int, two parameters may be string type, separate design two comparison function will be more cumbersome, at this time, we use the function template.
Template<typename t>
int cmp (t A, T b) {
Return a>b;
}

(1) Each time a call is made, the compiler infers the template parameters to instantiate a specific version of the function for us, and T can be replaced with any type.
(2) The template can be replaced by class, and the function of two is the same.

Class template

Defining class Templates

The definition of a class template is similar to that of a template function, but it is slightly different when declaring an object

Template<typename T>class gg{
Public:

T A;

GG (T aa): A (AA) {};

};

Gg<string> g ("ASA"); Declarations section

Non-type template parameters

In addition to defining type parameters, you can define non-type parameters in a function, and a non-type parameter represents a value rather than a type.

For example

Template<typename T, unsigned n>class gg{
Public:
T A;
GG (T aa): A (AA) {};
int aa ();
};

Inline and constexpr function templates

As with normal defined functions, the inline or constexpr is written before the function body type after the template.

member functions for class templates

Template<typename T, unsigned n>//= Next is a template

int gg<t, N>::AA () {//through gg<t, n> find the class corresponding to the function
for (int i = 0;i < n; i++) printf ("gaofangzuishuai\n");
return A;
}

HLW's C + + learning Notes template and generic programming

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.