指向类模板方法的 void 指针的向量

Vector of void pointer to class template method

本文关键字:void 向量 指针 模板方法      更新时间:2023-10-16

im 在 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,但有了它,我无法为我想调用的每个类模板的函数定义一个向量。

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

提前感谢!

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

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

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

在您的情况下,看起来createComponent将是虚拟方法。