【问题标题】:Vector of void pointer to class template method指向类模板方法的 void 指针向量
【发布时间】:2017-10-16 21:34:09
【问题描述】:

我正在开发一个 DataManager,可以在其中注册组件,这会创建一个 Buffer<Component>。这是可行的,但为了保存缓冲区,我有一个std::vector<char*>,因为我不能在同一个向量中保存不同类型的类模板。

        //register Components and return reference to them (Pre-Init Phase)
    template<class TComponent>
    ComponentID registerComponent(std::string Name = "",int ComponentNr = COMPONENTNR) {

        //Create Buffer<TComponent> with rising ID Counter
        ComponentContainer<TComponent>* t = new ComponentContainer<TComponent>(_componentIDCounter++, ComponentNr);

        //Add Buffer ptr to vector
        _container.push_back(reinterpret_cast<char*>(t));

        //return ComponentID
        return t->getComponentID();
    };

现在我希望 DataManager 成为一个用于创建和删除组件的大型包装类。为此,我想保存一个指向新创建缓冲区的 createComponent 方法的指针。 问题是,我不能为给定的方法定义一个向量......

typedef void (*CreatesPtr)(int);
...
CreatesPtr f = t->createComponent;

...这不起作用,因为它认为我想创建一个指向成员而不是方法的指针,或者我可以使用 std::bind 来绑定它,因为 std::bind ,但是这样我就不能为每个类模板要调用的函数定义一个向量。

也许我的方式很愚蠢,并且更容易实现其他方式,所以任何建议都值得赞赏,但如果有办法使这项工作我肯定会更喜欢。

提前致谢!

【问题讨论】:

    标签: c++ visual-studio c++11 pointers vector


    【解决方案1】:

    你一开始是从一个未陈述的和不正确的假设开始的。

    类模板可以从非模板基类派生。您可以将指向此基类的指针存储在向量中。

    基类可以有纯virtual 方法,您可以调用向量的元素。类模板将实现这些virtual 方法,可能就其模板参数而言。

    在您的情况下,createComponent 似乎是虚拟方法。

    【讨论】:

    • 我的Buffer不是派生类,ComponentContainer是派生类,它通过调用Buffer::createObject(int ID实现了ComponentContainer::createComponent(int ID) )。因此,如果我没有错,我不能使该功能虚拟化。
    • @PSquall:我的声明是制作 Buffer&lt;Component&gt; 一个派生类,并从一个新的BufferBase 派生它。这仅用于定义virtual CreatesPtr BufferBase::createComponent(int) = 0
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-04
    相关资源
    最近更新 更多