使用类型推导向下转换到子类的方法

问题描述

问题的关键是我想创建一个基指针向量来引用子对象。但是,我在访问孩子们的方法时遇到了问题。我在网上看到过向下转型的例子,但我觉得这对我来说不是最好的事情,因为我想保持我的代码通用。请查看下面的示例,了解我正在尝试完成的工作。

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)
    {
    }
    U getFunction() const {return m_getter();}
    void setFunction(U input) const {return m_setter(input);}

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
}

在上面的这个例子中,我的向量大小为 2,这是可管理的,但我的目标是将 c++ 类序列化到 psql 服务器,并且可能必须处理大小为 30+ 的向量。我的下一个问题是,考虑到可能需要为 typename U 执行的类型推导,有没有办法在 for 循环中自动执行此操作。

int main()
{
    std::vector<std::shared_ptr<Base>> Dummy = {std::make_shared<Child<int>> (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
     }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)