C ++ template Definition

Source: Internet
Author: User

When I first learned C ++, the template was placed in chapter 11th, and I didn't learn it well. Of course I had to learn it again with such a powerful tool! The following is a summary of the C ++ template definition:

 

Generally, C ++ Templates include function templates and class templates. The following describes

 

1. Function template definition:

Template <typename T>

 

Return type function name <t & A, T & B>

{

}

In the evolution process of C ++ language, the keyword typename appears relatively late. Before it, the keyword class is the only way to introduce type parameters and remains valid. Therefore, you can replace typename with class in the template as follows:

Template <class T>

Return type function name <t & A, T & B>

{

}

Here, the class does not mean that only the class can be used as an alternative, and the basic type can also be used.

Definition example:

// Max. HPP (the essence of HPP is. CPP implementation code. h. In the header file, the definition and implementation are included in the same file. Then, the caller of this class only needs to include the CPP file, and no need to add CPP to the Project for compilation. The implementation code will be directly compiled into the caller's OBJ file, and no separate OBJ will be generated. Using HPP will greatly reduce the number of CPP files and the number of compilations in the called Project, it does not need to release annoying lib and DLL, so it is very suitable for compiling public open-source libraries .)

Template <typename T>

 

Inline t const & max <t & A, T & B>

{

Return a <B? B:;
}

 

2. class template Definition

Template <typename T>

 

Class Stack {

}

Change typename to class.

Definition example:

Template <typename T>

 

Class Stack {

PRIVATE:

STD: vector <t> elems;

Public:

Stack ();

Void push (T const &);

Void POP ();

T top () const;

}

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.