函数指向模板类成员函数的指针

编程入门 行业动态 更新时间:2024-10-26 02:25:25
本文介绍了函数指向模板类成员函数的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个模板类(部分)定义为

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>);

更多推荐

函数指向模板类成员函数的指针

本文发布于:2023-07-28 02:44:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1226567.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   指针   模板   成员

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!