I think what you are looking for is simply, std::queue<std::unqiue_ptr<PlaneObj>>
.
i.e.
std::queue<std::unique_ptr<PlaneObj>> queue;
queue.push(new PlaneObjType1());
queue.push(new PlaneObjType2());
queue.push(new PlaneObjType3());
Question
I'm working on a project converting some code from a simulation language called MODSIM to C++ and have come across something I'm struggling to understand.
An example of the code is:
PlaneQueueObj = OBJECT(QueueObj[ANYOBJ:PlaneObj])
What this means is that we are declaring a class PlaneQueueObj
which is inheriting from QueueObj
, which only allows objects of class PlaneObj
or classes derived from PlaneObj
into the queue. (Classes are called objects in this language...)
I want to know how this can be implemented in C++
.
It could be really obvious and I've just got myself confused but I'm new here so go easy.
Solution
I think what you are looking for is simply, std::queue<std::unqiue_ptr<PlaneObj>>
.
i.e.
std::queue<std::unique_ptr<PlaneObj>> queue;
queue.push(new PlaneObjType1());
queue.push(new PlaneObjType2());
queue.push(new PlaneObjType3());
OTHER TIPS
Would something like this do it?
I suppose that your queue is doing something special so that you need to implement one by yourself.
DISCLAIMER: I never wrote templates so I could be completely wrong;)
#include <vector>
#include <iostream>
template<typename T>
class QueueObj
{
private:
std::vector<T> queue;
public:
void Enqueue(const T &t)
{
queue.push_back(t);
}
T Dequeue()
{
T t = queue.back();
queue.pop_back();
return t;
}
};
class PlaneObj
{
public:
virtual void Print()
{
std::cout<<"PlaneObj"<<std::endl;
}
};
class PlaneObjDerived : public PlaneObj
{
public:
virtual void Print()
{
std::cout<<"PlaneObjDerived"<<std::endl;
}
};
class PlaneQueueObj : public QueueObj<PlaneObj*> {};
int main()
{
PlaneQueueObj queue;
PlaneObjDerived *po1 = new PlaneObjDerived;
PlaneObjDerived *po2 = new PlaneObjDerived;
queue.Enqueue(po1);
queue.Enqueue(po2);
// queue.Enqueue(10); // ERROR: error C2664: 'QueueObj<T>::Enqueue' : cannot convert parameter 1 from 'int' to 'const PlaneObj &'
po1 = static_cast<PlaneObjDerived *>(queue.Dequeue());
po2 = static_cast<PlaneObjDerived *>(queue.Dequeue());
po1->Print();
po2->Print();
return 0;
}