如何使用"Curiously recurring template"模式

How to use the "Curiously recurring template" pattern

本文关键字:template 模式 recurring Curiously 何使用      更新时间:2023-10-16

我不确定是否允许提出这样的问题。但是我真的不能理解应该在我的程序中使用的代码。

这种情况是,我必须应用一个早期编写的类,它是由某种模式设计的,我无权更改它。不幸的是,我不知道它是哪种模式,也不知道如何使用它。

(这个故事是关于一个链表模板的。)

代码是这样的:

template<typename T> class LListNode {
public:
LListNode();
void setNext(T*);
...
T* next() const;
};
template<typename T> inline void LListNode<T>::setNext(T* next) {
static_cast<T*>(this)->m_next = next;
}
...

这是节点类,下一个是主列表类:

template<typename T> class LList {
public:
LList();
bool isEmpty() const;
...
T* head() const;
...
void push(T*);
...
private:
T* m_head;
T* m_tail;
};

首先,我尝试用自己的类作为模板类来实例化LList类。但这并没有奏效。我认为也许我自己的类(将存储在List中)应该从LListNode类继承。这似乎是个好主意,但后来我陷入了困境。

如何定义从另一个类继承的类,该类将当前定义的类作为模板参数

只是为了说明一下:

class Foo : LListNode<Foo> {
private:
Foo* m_next;
public:
...

在这一点上,我的编译器(gcc(Ubuntu/Linaro 4.6.4-1ubuntu12.04)4.6.4)正在哭泣:

In instantiation of 'void LListNode<T>::setPrev(T*) [with T = Foo]': 
required from LListNode<T>::LListNode() [with T = Foo]'
Foo.h:   required from here
LList.h: error: LListNode<Foo>' is an inaccessible base of 'Foo'

您忘记了public:

class Foo : public LListNode<Foo> {
private:
Foo* m_next;
public:
...