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.