在同一接口中包装不同的 std::vector<T>

Wrap different std::vector<T> in same interface

本文关键字:vector gt lt 接口 包装 std      更新时间:2023-10-16

我有 2 个类用于管理 2 个不同类型的队列(以list<myType1*>list<myType1*>的形式(。 为了简化情况,我们可以在这里使用std::vector<std::string>std::vector<int>如下例所示:

class StringQueue
{
public:
StringQueue();
~StringQueue();
int count() const {return m_queue.size();}
void add(std::string item) {m_queue.push_back(item);}
void clear() {m_queue.clear();}
...etc...
protected:
std::vector<std::string> m_queue;
};
class IntQueue
{
public:
IntQueue();
~IntQueue();
int count() const {return m_queue.size();}
void add(int item) {m_queue.push_back(item);}
void clear() {m_queue.clear();}
...etc...
protected:
std::vector<int> m_queue;
};

对于每个Queue类,我都有许多访问队列的功能(添加、清除、计数、检查、弹出一个、弹出多个等......

查看代码,我现在的问题是:是否可以在这里使用继承? 我知道我可以实现一个Queue基类,但只能派生几个函数(count()在上面的例子中(,因为m_queue对象是不同的,即使函数(addclear等(是相同的。 即使std::vector元素不同,是否有可能具有完整的函数继承?

我在想这样的事情:

class Queue
{
public:
Queue();
~Queue();
int count() const {return m_queue.size();}
void add(T item) {m_queue.push_back(item);}
void clear() {m_queue.clear();}
...etc...
protected:
std::vector<T> m_queue;
};

有没有办法实现这一目标?

这是模板的完美工作:

template<class T>
class MyQueue
{
public:
MyQueue();
~MyQueue();
int count() const {return m_queue.size();}
void add(T item) {m_queue.push_back(item);}
void clear() {m_queue.clear();}
T popOne()
{
T front = m_queue.front();
m_queue.erase(m_queue.begin());
return front;
}
...etc...
protected:
std::vector<T> m_queue;
};

继承不是适合这项工作的工具,原因表明了自己的身份。

然而:

  1. 你为什么不使用已经完全完成这种包装的std::queue和朋友?
  2. 为什么要基于std::vector构建队列 - 从前面擦除元素涉及将其他元素向前移动一个插槽。这和它得到的一样昂贵...

如果您想进一步使用模板,我建议您阅读更多有关模板的信息。虽然上面的代码看起来很好而且很容易,但在C++中编写模板化代码有其自身的一系列挑战。