Одно из возможных решений, чтобы сделать List
базовый класс обрабатывать только узлы, то есть следить за О.Г. список головы, хвост и добавление/удаление узлов. Класс List
может иметь базовый класс Node
, который наследуется, например. IntList
по специализации.
Что-то вроде
class List
{
public:
virtual ~List() {}
protected:
// Protected constructor so this class can only be inherited
List() {}
struct Node
{
Node* next;
Node* prev;
};
void add_head(Node*);
void add_tail(Node*);
Node* pop_head();
Node* pop_tail();
Node* get_head();
Node* get_tail();
private:
Node* head;
Node* tail;
};
class IntList : public List
{
public:
IntList();
~IntList();
void add_head(int); // Creates an `IntNode` and calls `add_head` with that
void add_tail(int); // Creates an `IntNode` and calls `add_tail` with that
int pop_head(); // Calls `pop_head` to get the node, and downcast to `IntNode`
int pop_tail(); // Calls `pop_tail` to get the node, and downcast to `IntNode`
int get_head(); // Calls `get_head` to get the node, and downcast to `IntNode`
int get_tail(); // Calls `get_tail` to get the node, and downcast to `IntNode`
private:
struct IntNode : List::Node
{
int value;
};
};
Да, конечно, это возможно. Но не будут ли шаблоны лучше? –
@JoachimPileborg Вы абсолютно правы, шаблоны лучше, но мне любопытно узнать, как это возможно, используя наследование. –
Если вы создаете связанный список с использованием наследования, из-за увеличения/понижения, для каждой версии существует много реализаций. стихи с шаблонами, просто автоматические. – sp2danny