指向模板类成员函数的函数指针
我有一个模板类(部分)定义为
template <class T> MyClass
{
public:
void DoSomething(){}
};
如果我想从另一个类调用 DoSomething,但能够在同一位置对多个“T”类型执行此操作,我就陷入了一个想法,因为方法函数指针是唯一的受限于类类型。 当然,每个 MyClass 都是不同的类型,因此我无法以“多态”方式存储指向 MyClassDoSomething() 的函数指针。
我的用例是我想在一个持有类中存储一个指向“DoSomething”的函数指针向量,这样我就可以从一个地方对所有存储的类发出调用。
有人有什么建议吗?
I have a templated class defined (in part) as
template <class T> MyClass
{
public:
void DoSomething(){}
};
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.
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.
Has anyone any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你知道,这正是我需要做的。 奇怪的是,我很早就将其视为对我的用例有效的解决方案,但现在我不知道原因。 我想我被我在同一个地方为编译时调度所做的一些元编程的东西蒙蔽了(即在我混乱的大脑中混淆了编译时间和运行时)。
谢谢你的震动!
You know, that is just what I needed to do. Bizzarly I had discounted it as a solution valid for my usecase early on, for reasons that now escape me. I think I was blinded by some metaprogramming stuff I'm doing in the same place for compile-time dispatch (i.e. confusing compile time and runtime in my addled brain).
Thanks for the jolts!
好的,所以函子解决方案无法按您的需要工作。 也许您应该让您的模板类继承自公共基“Interface”类。 然后你使用这些向量。
像这样的东西:
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.
Something like this: