Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve objects pointers of different type

Tags:

c++

c++14

folly

Consider I have a bunch pointers to to different objects of different classes

class1* obj1;
class2* obj2;
class3* obj3;

and they all have one method getArray() which returns a vector for post processing.

if all of these pointers are stored in some sort of a list (a list of void pointers say)

while I am iterating the list is there a way to figure what type of a pointer cast can be used?

I understand this can be solved by class hierarchy and deriving the above classes from a single class. Since a lot of it is legacy code can something like what is mentioned be done?

Folly dynamic does not let me store pointers, thats one thing that is tried

like image 623
ajax_velu Avatar asked Sep 03 '26 07:09

ajax_velu


1 Answers

If getArray() always has the same signature (or similar enough to cast to the same type) - what you could do is create a class hierarchy for a decorator of the duck-typed legacy objects/classes. You can use a template derived class of a non-template interface to wrap without too much typing work.

Something along these lines (with more defensive coding, possibly smart pointers to the legacy object, etc. etc.):

class IDecorator {
  public:
    virtual std::vector<ubyte> GetArray() = 0;
};

template<typename TLegacyType>
class TDecorator : public IDecorator {
   public:
     TDecorator(const TLegacyType *ip_legacy_object)
       : mp_legacy_object(ip_legacy_object) {}
     std::vector<ubyte> GetArray() override {
        return mp_legacy_object->GetArray();
     }

   private:
     const TLegacyType *mp_legacy_object;        
};
like image 174
Joris Timmermans Avatar answered Sep 05 '26 20:09

Joris Timmermans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!