gpt4 book ai didi

c++ - 嵌套类作为模板参数

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:40:07 26 4
gpt4 key购买 nike

我尝试编写一个自定义 STL 样式的容器。为了简单起见,假设它是一个列表。我查找了定义此类容器的标准方法:

template <typename T, typename A = std::allocator<T> > class mylist;

现在,我想使用嵌套类来管理列表的节点:

(inside mylist)
class node {
T data;
node *next;
}

据我了解,我不需要输入 template node 定义前的说明符因为编译器将实例化单独的类 mylist<T,A>::node对于 mylist 的每个组合的模板参数。

但是,现在我不仅需要为 T 类型的数据分配内存本身,也为他们的包装node .因此,我希望默认模板参数的类型为 std::allocator<mylist<T>::node> .不过,那时,mylist尚未声明,编译器很不高兴,这是可以理解的:

error: `mylist' was not declared in this scope

如何解决这个难题?有两个约束:

  • 通常,我会在不完整声明其内容的情况下声明缺少的类。但是,由于它嵌套在我要声明的内容中,所以这不是一个选项。
  • 我需要 node嵌套,因为它需要访问 mylist 的分配器实例.例如,我有 operator=声明于 node很多内存管理都是递归发生的。这对于列表来说可能有点矫枉过正,您可以在 mylist 中执行此操作,从而降低了 node 的参数依赖性在 A ,但这对我正在实现的数据结构至关重要。

最佳答案

默认分配器的类型参数是什么并不重要,重要的是实际类型。您可以使用 rebind_alloc 来自 std::allocator_traits :

Alloc::rebind<T>::other if present, otherwise Alloc<T, Args> if this Alloc is 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>;
};

然后使用NodeAlloc得到你的node秒。这样,如果用户没有指定分配器,您将获得默认的 std::allocator<T>然后使用 std::allocator<node> .这正是您想要的,而不必暴露 node .

关于c++ - 嵌套类作为模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33677406/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com