在同一接口中包装不同的 std::vector<T>
Wrap different std::vector<T> in same interface
我有 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对象是不同的,即使函数(add
、clear
等(是相同的。 即使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;
};
继承不是适合这项工作的工具,原因表明了自己的身份。
然而:
- 你为什么不使用已经完全完成这种包装的
std::queue
和朋友? - 为什么要基于
std::vector
构建队列 - 从前面擦除元素涉及将其他元素向前移动一个插槽。这和它得到的一样昂贵...
如果您想进一步使用模板,我建议您阅读更多有关模板的信息。虽然上面的代码看起来很好而且很容易,但在C++中编写模板化代码有其自身的一系列挑战。
相关文章:
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 在c++中用vector填充一个简单的动态数组
- vector.resize()中的分配错误
- 使用std::vector的OpenCL矩阵乘法
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 在某些循环内使用vector.push_back时出现分段错误
- 当vector是tje全局变量时,c++中vector的内存管理
- std::vector的包装器,使数组的结构看起来像结构的数组
- 为什么(-1)%vector::size()总是返回0
- 在C++中将类(带有Vector成员)保存为二进制文件
- 编译器如何区分std::vector的构造函数
- 将 int 数组转换为 std::vector<int*>
- 使用 pqxx 将 std::vector 存储在 postgresql 中,并从数据库中检索它
- EASTL矢量<向量<int>>连续的
- 在std::vector上存储带有模板的类实例
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ
- std::vector<;uint8_t>;当C++11/14启用时,手动复制而不是调用memcpy
- 使用 std::vector<boost::shared_ptr<Base_Class>> 或 boost::p tr_vector 的性能注意事项是什么<Base>
- 将矩阵"shared_ptr<vector<vector>sp"的行"(*sp)[i]"<T>传递给接受"shared_ptr<vector<T>>
- 如何获取std::vector<DMatch>