问题描述
我有一个模板类(部分)定义为
I have a templated class defined (in part) as
template <class T> MyClass
{
public:
void DoSomething(){}
};
如果我想从另一个类调用DoSomething,但是能够为多个'T'类型在同一个地方,我被困住一个想法作为方法函数指针唯一约束到类类型。当然,每个MyClass是一个不同的类型,所以我不能以'多态'的方式存储函数指针MyClassDoSomething()。
If I want to call DoSomething from another class, but be able to do this for multiple 'T' types in the same place, I am stuck for an idea as method functions pointers are uniquely constrained to the class type. Of course, each MyClass is a different type, so I can not store function pointers to MyClassDoSomething() in a 'polymorphic' way.
我的用例是我想要的在一个持有类中存储一个函数指针的向量到'DoSomething',这样我可以从一个地方发出对所有存储类的调用。
My use-case is I want to store, in a holding class, a vector of function pointers to 'DoSomething' such that I can issue a call to all stored classes from one place.
任何人任何建议?
推荐答案
确定,所以函子解决方案不能按照需要工作。也许你应该让你的模板类继承自一个通用的基础接口类。然后你使用那些的向量。
Ok, so the functor solution doesn't work as you need. Perhaps you should have your template class inherit from a common base "Interface" class. And then you use a vector of those.
这样的东西:
class Base {
public:
virtual ~Base(){}
virtual void DoSomething() = 0;
}
template <class T> class MyClass : public Base {
public:
void DoSomething(){}
};
std::vector<Base *> objects;
objects.push_back(new MyClass<int>);
objects.push_back(new MyClass<char>);
这篇关于函数指向模板类成员函数的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!