Should template parameters be types?

The Bjarne Stroustrup C ++ book (chapter 13, p. 331) states that "a template parameter can be used to define a subsequent template parameter." And he gives the following code:

template<class T, T def_val> class Cont{ /* ... */ } 

Can anyone provide an example of using this template. For example, how to initialize a Cont object? It seems to me that "def_val" is not a type argument and should not be placed in <>. I am wrong?

thanks a lot

+6
source share
4 answers

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 do not have 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.), Riga mentioned in her comment.

+7
source

def_val is the argument of the value. Replication might look like this:

 Cont<int, 1> foo; 

An interesting case when this is useful is that you want to have a pointer to a class member as a template template:

 template<class C, int C::*P> void foo(C * instance); 

This allows you to create foo with a pointer to an int element of any class.

+6
source

Here is an example of how to instantiate the above:

 template<class T, T def_val> class Cont{ /* ... */ }; int main() { Cont<int,42> c; } 
+3
source

T def_val is an object of type T (which was previously passed). It can be used to initialize elements in a container, for example. For use, it would look like this:

 Object init(0); Cont<Object, init> cont; 

(psuedo-code; Object should obviously be a type that is legal to use in this way)

Then the second template parameter is used. It is included in the template because it has a template type; def_val must be of type T and must be passed when the object is created.

+2
source

Source: https://habr.com/ru/post/897930/


All Articles