指向基类的共享指针,其中子类是模板类

问题描述

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

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.
}

有没有一种方法可以访问 C++11 中的这些公共方法,而无需向下转换并在这样做时指定类型 U

解决方法

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

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

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