Must template parameters be types?
In the Bjarne Stroustrup C++ Book 开发者_Python百科(chapter 13, page 331), it said that "a template parameter can be used in the definition of subsequent template parameter". And it gives the following code:
template<class T, T def_val> class Cont{ /* ... */ }
Can anyone provide an example of how to use this template. For example, how to initialize an object of Cont? It look to me that "def_val" is not a type argument, and should not be placed in <>. Am I wrong?
Thanks a lot
You can do something like this:
Cont<int, 6> cnt;
// ^ as long as this is of type T (in this case int)
// def_val will be of type int and have a value of 6
Template parameters aren't required to be types.
This only works when T
is an integral type (int
, unsigned
, long
, char
etc but not float
, std::string
, const char*
, etc), as @Riga mentioned in his/her comment.
def_val
is a value argument. An instantiation could look like this:
Cont<int, 1> foo;
An interesting case where this is useful is when you want to have a pointer to a class-member as template paremeter:
template<class C, int C::*P>
void foo(C * instance);
This enables foo
to be instantiated with a pointer to a member of type int
of any class.
Here's an example of how to instantiate the above:
template<class T, T def_val> class Cont{ /* ... */ };
int main()
{
Cont<int,42> c;
}
T def_val
is an object of type T
(which was previously passed). It could be used to initialize items in the container, for example. To use, it would look something like:
Object init(0);
Cont<Object, init> cont;
(psuedo-code; Object
must obviously be a type that's legal to use in this manner)
That then uses the second template parameter. It's included in the template because it has a templated type; def_val
must be of type T
and must be passed when the object is created.
精彩评论