如何使用"Curiously recurring template"模式
How to use the "Curiously recurring template" pattern
我不确定是否允许提出这样的问题。但是我真的不能理解应该在我的程序中使用的代码。
这种情况是,我必须应用一个早期编写的类,它是由某种模式设计的,我无权更改它。不幸的是,我不知道它是哪种模式,也不知道如何使用它。
(这个故事是关于一个链表模板的。)
代码是这样的:
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:
...
相关文章:
- 表示"accepting anything for this template argument" C++概念的通配符
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 为什么在保护模式下继承升级不起作用
- 如何在全屏模式下(在OpenGL中)使背景透明
- 为什么使用__LINE_的代码在发布模式下在MSVC下编译,而不是在调试模式下
- 派生类是否可以在抽象工厂设计模式中具有数据成员
- 此模式的C++RegEx
- avrogencpp能为模式中的每种类型生成单独的头文件吗
- 使用可变模板的Broadcaster/Listener模式
- 传递给std::function template的template参数究竟代表什么
- c++方法参数只能在linux的发布模式下自行更改
- 在template中使用std::variant的template函数
- 资源管理设计模式
- 使用 mod_gsoap 部署服务时,如何在 Gsoap 中更改 soap 上下文的模式?
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 小字符串优化(调试与发布模式)
- 可视化C++:发布模式的运行时库作为'Multi-threaded Debug DLL'
- 如何设计具有不同类型的通知和观察器的观察者模式?
- 如何使用"Curiously recurring template"模式
- 使用 CRTP 和'anonymous types/template'实现观察者模式