hally9k
hally9k

Reputation: 2583

What does a second specified type mean in a template typename declaration?

I am comfortable with templating functions and classes but I didn't know what to make of this when I saw it. I am sure its probably everyday syntax to most but I would like to get a well clarified explanation if anyone has one for me. What does the second uint32-t max mean and how is it used in the templated type?

Heres the syntax:

template <typename T, uint32_t max>

Thanks in advance.

Upvotes: 4

Views: 460

Answers (5)

Some programmer dude
Some programmer dude

Reputation: 409404

It's so you can specify a non-type value as a template argument.

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

For example

std:array<int, 256> my_array;

Do note that you can't use any types as value template arguments, it's basically limited to pointers, references and integer values.

Upvotes: 8

nikolas
nikolas

Reputation: 8975

You can use types, integral values, or even templates as template parameters. There are lots of reasons why and how this could be used, and it's impossible to tell you what it does in your specific case.

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

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

Upvotes: 5

James Kanze
James Kanze

Reputation: 154007

It's a second parameter to the template. And template parameters don't have to be types. They can be constants or templates as well. Thus, given

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

you would instantiate it:

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 deduction can be used to determine the (numeric) value of max.

Such value templates cannot have just any type; it must be an integral type or a pointer or reference.

Upvotes: 12

dunc123
dunc123

Reputation: 2723

The second parameter is a uint32_t rather than a type. For example it might specify the number of elements in an array.

template <typename T, uint32_t max>
struct Array
{
    T data[max];
};

/* ... */

// usage example 
Array<double, 10> a;

Upvotes: 10

Oswald
Oswald

Reputation: 31685

The second uint32_t max means, that when instantiating the template, you have to pass a second template argument of type uint32_t that is known at compile time.

Upvotes: 3

Related Questions