开发者

Template declaration explanation

开发者 https://www.devze.com 2023-01-24 00:19 出处:网络
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

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


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


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> >
0

精彩评论

暂无评论...
验证码 换一张
取 消