vendredi 7 janvier 2022

C++ how to make polymorphic wrapper class around smart pointer?

Hello I am writing code for school project. In my current implementation I am using polymorphism in some cases. Like for example when I have a set or a vector:

std::vector<Parent *> vec;
vec.push_back(new Child1()); // adding instance of derived class
vec.push_back(new Child2()); // adding other instance of derived class

I can use this code to add objects of derived classes, but in case of using a set for example, I cannot prevent duplicated by using this method, because the set will compare the memory address to another, not the objects themselves, so I want to use wrappers. On another note, my teacher suggests to use smart pointers, like unique_ptr or shared_ptr so that memory is properly cleaned up. I find the second option to be easier to work with. In any case even if I have:

std::set<std::shared_ptr<Parent>> s;
s.insert(std::make_shared<Child1>(Child1());
// ...
s.insert(std::make_shared<ChildN>(ChildN());

It still works just with regular pointers and duplicates are allowed. So I want to write a wrapper class to prevent this from happening and I have something like this:

template<typename T>
class PolymorphicWrapper {
private:
    std::shared_ptr<T> ptr;
public:
    PolymorphicWrapper(const std::shared_ptr<T> &ptr) : ptr(ptr) {}

    const std::shared_ptr<T> &getPtr() const {
        return ptr;
    }

    void setPtr(const std::shared_ptr<T> &ptr) {
        PolymorphicWrapper::ptr = ptr;
    }

    bool operator==(const PolymorphicWrapper &rhs) const {
        return *ptr == *rhs.ptr;
    }

    bool operator!=(const PolymorphicWrapper &rhs) const {
        return rhs != *this;
    }

    bool operator<(const PolymorphicWrapper &rhs) const {
        return *ptr < *rhs.ptr;
    }

    bool operator>(const PolymorphicWrapper &rhs) const {
        return rhs < *this;
    }

    bool operator<=(const PolymorphicWrapper &rhs) const {
        return rhs >= *this;
    }

    bool operator>=(const PolymorphicWrapper &rhs) const {
        return *this >= rhs;
    }
};

But this approach doesn't work with derived classes at all! For example:

std::set<PolymorphicWrapper<Parent>> s;
s.insert(PolymorphicWrapper<Parent>(std::make_shared<ChildN>(ChildN()); // doesn't work

Is there a simple fix? I am not too good with programming and have trouble understating hard solutions. But it is an exam I have to pass to keep going with other subjects.

Aucun commentaire:

Enregistrer un commentaire