A question about C++ template syntax (STL library source code)

c++, stl

Solution

The `template` keyword is needed to identify the name `rebind` as a class template. Without it, `rebind` could be considered a variable or a constant (in this case a type due to the `typename` keyword) and the following `<` could be interpreted as a less-than operator.

This is somewhat similar to the `typename` keyword (which is of course necessary to identify `other` as a type).

Every allocator is required to provide a meta-function (i.e. a class template) called `rebind` that returns the same allocator but for a different type. In other words,

Alloc<T>::rebind<U>::other

names the same type as

Alloc<U>

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?

Problem

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

Original source