mardi 30 mars 2021

method for downcasting to child class with type deduction

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.
    (dynamic_cast<Child<int>>(Dummy.at(0))->getGFunction(); // this is ok
}

In this example above my vector is of size 2 which is manageable but my goal is to serialize c++ classes to a psql server and may have to handle vectors of size 30+. My next question is is there a way to automate this in a for loop taking into the account the type deduction that may need to be performed for typename U.

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(...)) };
     std::vector<std::shared_ptr<Base>>::const_iterator it_base = Dummy.begin();
     for (; it_base != Dummy.end(); ++it_base)
     {
         //insert method here for downcasting
     }
}

Aucun commentaire:

Enregistrer un commentaire