Chenna V
Chenna V

Reputation: 10483

Template declaration explanation

I was looking at C++ STL vector template code to understand exactly how it is implemented. I have very basic understanding of template programming, could you give a clear explanation of the expression

typename _Alloc = std::allocator<_Tp> 

excerpt from STL vector as below:

template<typename _Tp, typename _Alloc = std::allocator<_Tp> >
class vector : protected _Vector_base<_Tp, _Alloc>

Thank you for all help

Upvotes: 1

Views: 183

Answers (2)

Diego Sevilla
Diego Sevilla

Reputation: 29021

This assigns a default type to a template parameter, so that you don't have to add it whenever you create a vector:

std::vector<int> v;

By default, the second parameter of the template is filled by the type std::allocator<_Tp>.

Default template parameters allow to shorten data declarations by including some default functionality (that you can override by simply giving a second parameter to the declaration of the template).

Upvotes: 2

James McNellis
James McNellis

Reputation: 355079

Class template parameters can have default arguments just as functions allow you to have default arguments for function parameters.

This allows you to use std::vector with only a single template argument, the value type, without having to specify the allocator explicitly, since most of the time you want the default allocator anyway.

This

std::vector<int>

is exactly the same as

std::vector<int, std::allocator<int> >

Upvotes: 1

Related Questions