(template) rebind<> 做什么?

新手上路,请多包涵

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

std::list<> 的某些基类中找到以下 typedef

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

其中“_Alloc”对应于分配器模板参数(和 _Ty 包含的类型)。我很难找到这个“关键字”的一个很好的解释。到目前为止我发现的最好的事情是它是分配器接口的一部分。尽管即使 cppreference 也不能很好地解释这一点。

这个 template rebind<> 有什么作用?为什么在那个位置有必要?

原文由 paul23 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
2 个回答

_Alloc 模板用于获取某种类型的对象。容器可能有内部需要分配不同类型的对象。 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分配一些节点类型的对象。 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 。使用

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

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

  1. 由于 rebind 是 --- 的成员模板,并且 _A _A 是模板参数,所以 rebind 为了表明依赖名称是一个模板,它需要加上前缀 template 。如果没有 template 关键字,则 < 将被视为小于运算符。
  2. 名称 other 也依赖于模板参数,即它也是一个依赖名称。为了表明从属名称是一种类型,需要 typename 关键字。

原文由 Dietmar Kühl 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

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

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

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

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

原文由 Foggzie 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题