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

2022-01-07 00:00:00 visual-studio c++ stl

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

trying to learn more about how the standard library is actually implemented I'm inspecting all containers in visual studio.. Here I see some curious structure:

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

In some base class of a std::list<> The following typedef is found

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

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

Where "_Alloc" corresponds with the allocator template argument (and _Ty the contained type). I have trouble finding a good explanation of this "keyword". Best thing I've found so far is that it is part of the allocator interface. Though even cppreference isn't very good in explaining this.

这个模板重新绑定<>有什么作用?为什么需要在那个位置?

What does this template rebind<> do? And why is it necessary at that location?

推荐答案

_Alloc 模板用于获取某种类型的对象.容器可能需要分配不同类型的对象.例如,当您有一个 std::list 时,分配器 A 旨在分配 T 类型的对象,但是std::list 实际上需要分配一些节点类型的对象.调用节点类型 _Tystd::list 需要为正在使用的 _Ty 对象获取分配器A 提供的分配机制.使用

The _Alloc template is used to obtain objects of some type. The container may have an internal need to allocate objects of a different type. 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 allocate objects of some node type. 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. Using

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

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

specifies the corresponding type. Now, there are a few syntactic annoyances in this declaration:

  1. 由于 rebind_A 的成员模板,_A 是模板参数,所以 rebind 成为一个依赖名称.要表明依赖名称是模板,它需要以template 为前缀.如果没有 template 关键字,< 将被视为小于运算符.
  2. 名称 other 也依赖于模板参数,即它也是一个依赖名称.要指示从属名称是一种类型,需要 typename 关键字.
  1. Since rebind is a member template of _A and _A is a template argument, the rebind becomes a dependent name. To indicate that a dependent name is a template, it needs to be prefixed by template. Without the template keyword the < would be considered to be the less-than operator.
  2. The name other also depends on a template argument, i.e., it is also a dependent name. To indicate that a dependent name is a type, the typename keyword is needed.

相关文章