1

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

James McNellis
  • 348,265
  • 75
  • 913
  • 977
Chenna V
  • 10,185
  • 11
  • 77
  • 104

2 Answers2

2

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).

Diego Sevilla
  • 28,636
  • 4
  • 59
  • 87
1

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> >
James McNellis
  • 348,265
  • 75
  • 913
  • 977
  • Thanks james. Do you know if there's any article or book that will explain, the design of STL code? I want to understand how the library is designed – Chenna V Nov 06 '10 at 17:30
  • 1
    @reddy: There is a [list of good C++ books](http://stackoverflow.com/questions/388242/the-definitive-c++-book-guide-and-list) here on Stack Overflow. Which would be most useful to you depends on what exactly you want to learn. – James McNellis Nov 06 '10 at 17:36