(模板)重新绑定<>做什么?

pau*_*l23 19 c++ stl visual-studio

试图更多地了解标准库是如何实现的我正在检查visual studio中的所有容器.在这里我看到一些奇怪的结构:

在a的某个基类中std::list<>找到以下typedef

typedef typename _Alloc::template rebind<_Ty>::other _Alty;
Run Code Online (Sandbox Code Playgroud)

其中"_Alloc"对应于allocator模板参数(和_Ty包含的类型).我很难找到这个"关键字"的好解释.到目前为止,我发现最好的是它是分配器接口的一部分.虽然甚至cppreference在解释这个问题上也不是很好.

这是template rebind<>做什么的?为什么在那个地方有必要?

Die*_*ühl 20

_Alloc模板用于获取某种类型的对象.容器可能具有分配不同类型的对象的内部需求.例如,当你有一个时std::list<T, A>,分配器A意味着分配类型的对象,Tstd::list<T, A>实际上需要分配某些节点类型的对象.调用节点类型_Ty,std::list<T, A>需要_Ty为使用提供的分配机制的对象获取分配器A.运用

typename _A::template rebind<_Ty>::other
Run Code Online (Sandbox Code Playgroud)

指定相应的类型.现在,这个声明中有一些语法上的烦恼:

  1. 由于rebind是其成员的模板_A_A是一个模板参数,rebind变成从属名称.要指示依赖名称是模板,需要以前缀为前缀template.没有template关键字,<将被视为小于运营商.
  2. 该名称other还取决于模板参数,即它也是依赖名称.要指示依赖名称是类型,typename需要关键字.


Fog*_*zie 8

rebind用于为与正在实现的容器的元素类型不同的类型分配内存。取自这篇 MSDN 文章

例如,给定类型为 A 的分配器对象 al,您可以使用表达式分配 _Other 类型的对象:

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

或者,您可以通过编写类型来命名其指针类型:

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


Mic*_*ser 6

stdc++ 代码中的示例:/usr/include/4.8/ext/new_allocator.h

rebind被定义为allocator类的结构体成员;该结构定义了一个成员other,它被定义为专门用于不同参数类型的分配器的实例(另一个成员定义了一个可以创建不同类型对象的分配器类)

 template<typename _Tp>
    class new_allocator
    {
    public:
      ...
      template<typename _Tp1>
        struct rebind
        { typedef new_allocator<_Tp1> other; };
Run Code Online (Sandbox Code Playgroud)

使用时:

  typedef typename _Alloc::template rebind<_Tp>::other _Tp_alloc_type;
Run Code Online (Sandbox Code Playgroud)

分配器的类型被引用为

  typename _Alloc::template rebind<_Tp>::other 
Run Code Online (Sandbox Code Playgroud)

现在,typedef 用于定义_Tp_alloc_type - 然后可以将其用作同一事物的较短名称。

一个示例用法是在 std::list 中,其中内部列表节点也需要其分配器,该分配器是从参数分配器重新定义的。