首页 > 解决方案 > 在以下容器中重新绑定的目的

问题描述

我正在阅读一些 C++ 代码,特别是试图理解一个定制的容器。

容器具有以下模板参数:

 template<typename T, typename Alloc>
 class container{ ... };

像orT之类的数据类型在哪里。这是分配器,可能是标准库之一。floatintAlloc

在该容器中,我发现以下内容:

 class Container{ ....
 template<typename NewType> 
  struct Rebind
   { 
      using newalloc = typename std::allocator_traits<Alloc>::template rebind_alloc<NewType>; 
      using Other    =       container<NewType, newalloc>
   }
 }

Rebind至少在任何地方都找不到明确使用的 struct 成员,我正在努力理解它的目的。

开发人员试图通过在容器中包含结构来实现什么?

标签: c++c++17allocator

解决方案


它不是数据成员。它是一个模板成员,它允许代码(它本身可能是一个模板)使用类似的分配器获得不同的容器类型。

例如,对每个元素应用一个函数以获得结果的新容器

template <typename Container, typename Function, typename Result = typename Container::template Rebind<std::invoke_result_t<Function, typename Container::const_reference>>::Other>
Result transform(const Container & container, Function function)
{
    Result result(container.get_allocator());
    for (auto & element : container) { result.push_back(function(element); }
    return result;
}

推荐阅读