试图更多地了解标准库是如何实际实现的,我正在检查 Visual Studio 中的所有容器。在这里,我看到了一些奇怪的结构:
在 std::list<>
的某些基类中找到以下 typedef
typedef typename _Alloc::template rebind<_Ty>::other _Alty;
其中“_Alloc”对应于分配器模板参数(和 _Ty 包含的类型)。我很难找到这个“关键字”的一个很好的解释。到目前为止我发现的最好的事情是它是分配器接口的一部分。尽管即使 cppreference 也不能很好地解释这一点。
这个 template rebind<>
有什么作用?为什么在那个位置有必要?
原文由 paul23 发布,翻译遵循 CC BY-SA 4.0 许可协议
_Alloc
模板用于获取某种类型的对象。容器可能有内部需要分配不同类型的对象。 For example, when you have astd::list<T, A>
, the allocatorA
is meant to allocate objects of typeT
but thestd::list<T, A>
actually needs to分配一些节点类型的对象。 Calling the node type_Ty
, thestd::list<T, A>
needs to get hold of an allocator for_Ty
objects which is using the allocation mechanism provided byA
。使用指定对应的类型。现在,这个声明中有一些语法上的烦恼:
rebind
是 --- 的成员模板,并且_A
_A
是模板参数,所以rebind
为了表明依赖名称是一个模板,它需要加上前缀template
。如果没有template
关键字,则<
将被视为小于运算符。other
也依赖于模板参数,即它也是一个依赖名称。为了表明从属名称是一种类型,需要typename
关键字。