如何使用 std::list 作为公开节点的列表的接口实现?

How to use std::list as the implementation of an interface for a list that exposes the nodes?

我有一个双向链表的接口,它暴露了它的边缘。例如:

template <typename T>
class Listnode
{
public:
    Listnode *prev;
    Listnode *next;
    T val;
};

template <typename T>
class List
{
public:
    Listnode *head;
    Listnode *tail;
    // insert, remove, etc.
};

假设外部旧代码使用这个接口。

我把std::list::sort的实现拿过来在List中模仿了。但是,如果可能的话,最好使用它而不是复制。

问题:是否可以使用std::list以某种方式实现List::sort?特别是,使用 std::list::sort 修改 ListListNodeprev-next 指针,使得 List 结束排序。好吧,基本上没有在 std::list.

中复制列表

我的回答:据我所知in the documentation, doesn't expose (see also this other question) the edges between nodes, except traversing them through its iterator, while its implementation of std::list::sort seems to modify directly the edges, or at least it works with the iterators until a call to a method (_M_transfer), like in the GNU implementation.[=我觉得从std::list开始就不可能了27=]

但我是初学者。我可能很容易遗漏一些东西。

您无法使 std::list 符合您的要求。最接近的做法是让 Listnode 类型中的 T 成为 std::list 中元素的 std::list<ActualT>::iterator。但是,如果现有代码正在使用此接口,而这些代码对 T 有自己的期望,那么这不是一个真正的选择。