I am reading STL source code right now.
Though I understand the meat in what I am reading in stl_list.h, I want to fully understand the following snippet (mainly related to the template syntax, I think).
template
class _List_base {
...
typedef typename _Alloc::template rebind<_List_node<_Tp> >::other _Node_Alloc_type; //(1).
...
typedef _Alloc allocator_type;
get_allocator() const
{ return allocator_type(*static_cast<
const _Node_Alloc_type*>(&this->_M_impl)); } // (2)
...
};
Can someone explain why we need a “template” following _Alloc in line (1)? (and giving a full explanation of this line?)
Can someone explain why we can cast _Node_Alloc_type to _Alloc in line (2)?
The
templatekeyword is needed to identify the namerebindas a class template. Without it,rebindcould be considered a variable or a constant (in this case a type due to thetypenamekeyword) and the following<could be interpreted as a less-than operator.This is somewhat similar to the
typenamekeyword (which is of course necessary to identifyotheras a type).Every allocator is required to provide a meta-function (i.e. a class template) called
rebindthat returns the same allocator but for a different type. In other words,names the same type as
The second part of your question is difficult to answer without more context. What is the type of
_M_impl? How is that type defined?