dimanche 8 mars 2020

C++ - How to return list of covariant classes?

I'm dealing with Qt + C++ (x11).

I have a base class, and several subclasses that return a new pointer to that subclass (covariant). I need to return too, an container (a QList) of these subclasses. An example:

class A
{
public:
    int id;
}

class B : public A
{
    int Age;
};

class WorkerA
{
public:
    virtual A *newOne() {return new A()};
    virtual QList<A*> *newOnes {
        QList<A*> list = new QList<A*>;
        //Perform some data search and insert it in list, this is only simple example. In real world it will call a virtual method to fill member data overriden in each subclass.
        A* a = this.newOne();
        a.id = 0;
        list.append(this.newOne()); 
        return list;
        };        
};

class WorkerB
{
public:
    virtual B *newOne() override {return new B()}; //This compiles OK (covariant)
    virtual QList<B*> *newOnes override { //This fails (QList<B*> is not covariant of QList<A*>)
        (...)
        };        
};

This will fail to compile, because QList is a completely different type from QList. But something similar would be nice. In real world, B will have more data members than A, and there will be C, D..., hence the need of "covariantate" the return of list. I will be much nicer:

WorkerB wb;
//some calls to wb...
QList<B*> *bList = wb.newOnes();
B* b = bList.at(0); //please excuse the absence of list size checking
info(b.id);
info(b.age);

than

WorkerB wb;
//some calls to wb...
QList<A*> *bList = wb.newOnes();
B* b = static_cast<B*>(bList.at(0)); //please excuse the absence of list size checking
info(b.id);
info(b.age);

Is there any way to achieve this?

Aucun commentaire:

Enregistrer un commentaire