Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does (template) rebind<> do?

trying to learn more about how the standard library is actually implemented I'm inspecting all containers in visual studio.. Here I see some curious structure:

In some base class of a std::list<> The following typedef is found

typedef typename _Alloc::template rebind<_Ty>::other _Alty; 

Where "_Alloc" corresponds with the allocator template argument (and _Ty the contained type). I have trouble finding a good explanation of this "keyword". Best thing I've found so far is that it is part of the allocator interface. Though even cppreference isn't very good in explaining this.

What does this template rebind<> do? And why is it necessary at that location?

like image 779
paul23 Avatar asked Jan 03 '13 23:01

paul23


2 Answers

The _Alloc template is used to obtain objects of some type. The container may have an internal need to allocate objects of a different type. For example, when you have a std::list<T, A>, the allocator A is meant to allocate objects of type T but the std::list<T, A> actually needs to allocate objects of some node type. Calling the node type _Ty, the std::list<T, A> needs to get hold of an allocator for _Ty objects which is using the allocation mechanism provided by A. Using

typename _A::template rebind<_Ty>::other 

specifies the corresponding type. Now, there are a few syntactic annoyances in this declaration:

  1. Since rebind is a member template of _A and _A is a template argument, the rebind becomes a dependent name. To indicate that a dependent name is a template, it needs to be prefixed by template. Without the template keyword the < would be considered to be the less-than operator.
  2. The name other also depends on a template argument, i.e., it is also a dependent name. To indicate that a dependent name is a type, the typename keyword is needed.
like image 184
Dietmar Kühl Avatar answered Sep 25 '22 01:09

Dietmar Kühl


rebind is for allocating memory for a type that differs from the element type of the container being implemented. Take from this MSDN article:

For example, given an allocator object al of type A, you can allocate an object of type _Other with the expression:

A::rebind<Other>::other(al).allocate(1, (Other *)0)

Or, you can name its pointer type by writing the type:

A::rebind<Other>::other::pointer

like image 33
Foggzie Avatar answered Sep 25 '22 01:09

Foggzie