C ++ templates Study Notes (3) -- Chapter 4, non-type template parameters

Source: Internet
Author: User

1 Chapter 4 Non-type template parameters

For function templates and class templates, template parameters are not limited to types. common values can also be used as template parameters.

1.1 Non-type class template parameters

For example:

Template <typename T, int maxsize>

Class Stack {

PRIVATE:

T elems [maxsize];

...

};

 

Int main ()

{

Stack <int, 20> int20stack;

Stack <int, 40> int40stack;

...

};

Each template instance has its own type, soInt20stackAndInt40stackThey belong to different types, and there is no explicit or implicit type conversion between these two types; therefore, they cannot be replaced with each other.

 

1.2 Non-type function template parameters

Template<TypenameT,IntVal>

T addvalue (TConst& X)

{

ReturnX + val;

}

STD: vector <Int> SRC;

STD: vector <Int> DEST;

SRC. push_back (1 );

SRC. push_back (2 );

DeST. Resize (5 );

STD: Transform (SRC. Begin (), SRC. End (), dest. Begin (), addvalue <Int, 5>); // 1

The last sentence is written as follows:

STD: Transform (SRC. Begin (), SRC. End (), dest. Begin (), (INT (*) (INT const &) addvalue <Int, 5>); // 2

After my verification in vs2005, you can simply write the 1 style.

1.3 Non-type template parameter restrictions

Generally, a non-type template parameter can be a constant INTEGER (including enumeration) or a pointer to an external linked object.

That is to say, floating point numbers cannot be used, and pointers to internal linked objects cannot be used.

So what is a pointer to an internal link object? The following is an example.

 

Template<Char Const* Name>

ClassMyclass {

...

};

 

Myclass <"Hello"> X;

The"Hello"Is an internal link object, because it is a literal constant. All literal constants are internal link objects.

 

If changed:

Extern Char ConstS [] ="Hello";

Myclass <S> X;

yes.

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.