What does the second type indicated in the declaration of the template template name mean?

I am comfortable working with templates of functions and classes, but I did not know what to do with it when I saw it. I am sure this is probably the everyday syntax for most, but I would like a well-explained explanation if anyone has one for me. What does the second uint32-t max value mean and how is it used in the template?

Here is the syntax:

template <typename T, uint32_t max> 

Thanks in advance.

+4
source share
5 answers

This is the second template parameter. And the template parameters do not have to be types. They can be constants or patterns. So given

 template <typename T, uint32_t max> class TC {}; 

you must create an instance:

 TC< MyClass, 42 > t; 

(for example.) Similarly, if it is a function template:

 template <typename T, uint32_t max> void tf( T (&array)[max] ); 
Type inference

can be used to determine the (numerical) value of max .

Such value patterns cannot be of any type; it must be an integral type or pointer or reference.

+12
source

The second parameter is uint32_t , not the type. For example, it can indicate the number of elements in an array.

 template <typename T, uint32_t max> struct Array { T data[max]; }; /* ... */ // usage example Array<double, 10> a; 
+10
source

That way, you can specify a non-type value as an argument to the template.

A good example is std::array , which contains two template arguments, the type of data contained and the size of the array.

for instance

 std:array<int, 256> my_array; 

Note that you cannot use any types as arguments to a value template, they are mostly limited to pointers, references, and integer values.

+8
source

You can use types, integral values, or even patterns as template parameters. There are many reasons why and how to use it, and it is impossible to tell you what it does in your particular case.

For example, consider this function, which returns a pointer to the end of an array (analogous to std::end for C arrays in C ++ 11):

 template <typename T, size_t k> T * end(T (& arr)[k]) { return arr + k; } 
+5
source

The second uint32_t max means that when creating an instance of the template, you need to pass the second argument to the template of type uint32_t , which is known at compile time.

+3
source

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


All Articles