vendredi 29 juillet 2016

c++ class for storing any class from class hierarchy

let's suppose i have class hierarchy. A; B1,B2,B3-Bn all derived from A, and some C classes derived from differrent B's. I want to have a class "UnifiedStorage" to store A derived classes, that should not be templated, but it should have std::shared_ptr inside himself and have two functions:

template <typename T>
setData(std::shared_ptr<T> data/* A's derived class */)

template <typename T>
std::weak_ptr<T> getData()

only possible realization i have found is to create smth like Keeper:

class UnifiedStorage{
    class Keeper {
    public:
        virtual ~Keeper (){
        }
    };

    template <typename DataType>
    class SpecificKeeper : public Keeper {
    public:
        SpecificKeeper (std::shared_ptr<DataType> data): data(data) {}
        ~SpecificKeeper() = default;
        std::shared_ptr<DataType> data;
    };

    template <typename SpecificDataType>
    void setData (std::shared_ptr <SpecificDataType> d) {
        keeper.reset( new SpecificKeeper <SpecificDataType> (d) );
    }
    template <typename RequestedDataType>
    std::shared_ptr <RequestedDataType> getData () {
        SpecificKeeper <RequestedDataType>* specificKeeper =  dynamic_cast <SpecificKeeper <RequestedDataType> * > (keeper.data());
        if (specificKeeper == nullptr){
            return std::shared_ptr <RequestedDataType> ();
        }else{
            return specificKeeper->data;
        }
    }

    private:
        std::unique_ptr<Keeper> keeper;
}

But this realization has strong negative. I only able to get shared_ptr to type that i have set in setData.

For example if a have called setData<B>(std::shared_ptr<B>) i can't getData<A> it returns null, but if I will call setData<A>(std::shared_ptr<B>) getData<A> will return correct pointer.

Aucun commentaire:

Enregistrer un commentaire