c++ - 在以下容器中重新绑定的目的
问题描述
我正在阅读一些 C++ 代码,特别是试图理解一个定制的容器。
容器具有以下模板参数:
template<typename T, typename Alloc>
class container{ ... };
像orT
之类的数据类型在哪里。这是分配器,可能是标准库之一。float
int
Alloc
在该容器中,我发现以下内容:
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 成员,我正在努力理解它的目的。
开发人员试图通过在容器中包含结构来实现什么?
解决方案
它不是数据成员。它是一个模板成员,它允许代码(它本身可能是一个模板)使用类似的分配器获得不同的容器类型。
例如,对每个元素应用一个函数以获得结果的新容器
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;
}
推荐阅读
- html - 如何在 django 中的安全过滤内容中使用模板标签
- javascript - 将 HTML 添加到 Google 折线图工具提示
- azure - Azure 服务总线队列与主题(发布/订阅)
- r-markdown - R markdown 在 .Rmd 中显示降价输出
- python - 在 QuerySet 中获取 TypeError / 预期字符串或类似字节的对象
- discord.js - Discord.js - 按字母顺序对角色进行排序
- c++ - 坏:C++#输入和输出调试
- python - 在 qss 定义中使用 FBS 的获取资源方法?
- c# - 如何将多个流复制到 1 以供客户端下载?
- javascript - Javascript:从相互关联的对象数组(A)创建一个新的对象数组(B)