Non-type template parameter -- nontype template parameters
The template parameters are not necessarily of the type or value. The following template is used as an example:
# Include <iostream> Usingnamespace STD; Template <typename T> T add (const T & A, const T & B) { Return A + B; } Void main () { Cout <"5 add 10 Is: "<add <> (5, 10) <Endl; } |
Parameter t indicates an unknown type, or t indicates a type.
A template parameter can also be a value. When a template parameter is a value, t represents an exact value. The following edge template can be used to specify the array size through parameters:
Template <typename T, int iarraysize> Class coo { Public: T arr [iarraysize]; }; |
Of course, we can specify the default value of this non-type parameter, such:
Template & lt; typename T, int iarraysize = 100 & gt; Class coo {}; |
The default value of iarraysize is 100.
Note that the function template is actually an overloaded function set. For the overloaded function set, the compiler cannot deduce its template parameter type, and the type must be explicitly specified, example of Edge:
STD: Transform (source. Begin (), source. End (), // start and end position of the source end
DeST. Begin (), // start position of the target end
(INT (*) (INT const *) addvalue <int, 5>); // operation
(INT (*) (INT const *) is the expression of the function pointer.
Note:
When using a non-type template parameter, it can only be an integer, including Enum, orPointer to an external link objectIf:
Template <float T>
Then, compilation fails.
There is a passage in the book:
Floating-point literals or a simple constant floating point expression (constant floating-point Expressions. Because there is no real work May be supported by C ++ in the future. For more information, see section 13.4. |
In addition, global pointers cannot be used as template parameters.
ForPointer to an external link object"How to understand this sentence? The following edge is used as an example:
# Include <iostream> Usingnamespace STD; Template <charconst * Name> Class myclass {}; Charconst s [] = "hello "; Void main () { Myclass <S> X; // No. S is an internal object. } |
The above is not acceptable, but it can be like this:
Extern char const * s [] = "hello ";
Because s with the extern keyword is no longer an internal object, but an external link.