Jon*_*ann 6 c++ containers templates stl
我尝试编写一个自定义STL样式的容器.为简单起见,我们说它是一个列表.我查找了定义这样一个容器的标准方法:
template <typename T, typename A = std::allocator<T> > class mylist;
Run Code Online (Sandbox Code Playgroud)
现在,我想使用嵌套类来管理列表的节点:
(inside mylist)
class node {
T data;
node *next;
}
Run Code Online (Sandbox Code Playgroud)
我的理解是,我不需要template在定义之前放置一个说明符,node因为编译器将为mylist<T,A>::node每个mylist模板参数组合实例化单独的类.
但是,现在我需要为类型T本身的数据分配内存,而且还需要为它们的包装器分配内存node.因此,我希望默认模板参数是类型std::allocator<mylist<T>::node>.但是,在那时,mylist尚未声明,编译器可以理解为难过:
error: `mylist' was not declared in this scope
Run Code Online (Sandbox Code Playgroud)
如何解决这个难题?有两个限制:
node嵌套,因为它需要访问分配器实例mylist.例如,我已经operator=声明node了许多内存管理递归发生的地方.对于列表而言,这可能是过度的,您可以从内部执行此操作mylist,从而降低nodeon 的参数依赖性A,但这对于我正在实现的数据结构至关重要.默认分配器的类型参数是什么并不重要,重要的是实际类型。您可以rebind_alloc使用std::allocator_traits:
Alloc::rebind<T>::other如果存在,否则Alloc<T, Args>如果这Alloc是Alloc<U, Args>
得到你需要的东西:
template <typename T, typename A = std::allocator<T> >
class mylist {
class node { ... };
using NodeAlloc = typename std::allocator_traits<A>::template rebind_alloc<node>;
};
Run Code Online (Sandbox Code Playgroud)
然后用它NodeAlloc来获取你的nodes。这样,如果用户没有指定分配器,您将获得默认分配器std::allocator<T>,然后使用std::allocator<node>. 这正是您想要的,而不必暴露node。
| 归档时间: |
|
| 查看次数: |
467 次 |
| 最近记录: |