mardi 30 mars 2021

shared pointer to a base class where child is a template class

The crux of the issue is I want to create a vector of base pointers to reference children objects. However I'm having issues accessing the methods of the children. I've seen examples of downcasting online but I don't feel it's the best thing for me since I want to keep my code generic. Please look below for a sample of what I'm trying to accomplish.

class Base
{
public:
    stuffx;
private:
    stuffy;
}

template<typename U>
class Child : public Base
{
public:
    Child(
          std::function<U()> getterFunc,
          std::function<void(U)> setterFunc
          ):
          mgetter(getterFunc),
          msetter(setterFunc)
    {
    }
    std::function<U()>& getGFunction() const {return m_getter;}
    std::function<void(U)>& getSFunction() const {return m_setter;}

private:

    observableValues() {}
    std::function<U()> m_getter;
    std::function<void(U)> m_setter;
}

int main()
{
    std::vector<std::shared_ptr<Base>> Dummy = {std::make_shared<Child<int>> (std::bind(..), std::bind(...)),
                                                std::make_shared<Child<string>> (std::bind(..), std::bind(...)) };
    Dummy.at(0)->getGFunction(); // this throws an error as out of scope.
}

Is there a way to get access to those public methods in C++11 without downcasting and specifying the type U when doing so?

Aucun commentaire:

Enregistrer un commentaire