需要某种方法将函数存储在列表中,然后调用它们
这个列表必须包含函数,它们可能来自不同的命名空间,甚至是实例化类的方法。
然后将迭代该列表并调用所有函数和方法。如果它们也可以包含参数,那就太好了。
我正在考虑使用 std::vector,但我怀疑我的猜测远不正确。
您推荐我什么方法?欢迎所有帮助。
This list, has to hold functions, they might be from different namespaces and even methods of instanced classes.
This list will then be iterated and all the functions and methods called. It would be nice if they could contain arguments also.
I was thinking on using a std::vector, but I suspect that I am far from correct in that guess.
What approach do you recommend me? All help is welcome.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您的编译器已经支持 std::function 和 std::bind ,您可以使用它。
You could use std::function and std::bind if your compiler already supports it.
让所有函数都实现 命令模式。
当您
迭代列表中,您调用每个列表项的 Execute() 方法。
例如,假设您有一个名为 Commander 的简单命令界面:
并且您想要将三个对象放入列表中:灰狗、灰隼和女朋友。将每个对象包装在调用该对象感兴趣的函数的 Commander 对象中。灰狗奔跑:
灰隼飞翔:
女朋友尖叫:
将指挥官对象填入您的列表中。现在您可以迭代它们并调用每个元素的 Execute() 方法:
Have all of your functions implement the Command Pattern.
Your list becomes a
As you iterate over the list, you invoke the Execute() method of each list item.
For example, say you have a simple Command interface called Commander:
And you have three objects that you want to put in your list: A Greyhound, a Gyrefalcon, and a Girlfriend. Wrap each in a Commander object that calls the object's function of interest. The Greyhound runs:
The Gyrefalcon flies:
And the Girlfriend squawks:
Stuff the Commander objects in your list. Now you can iterate over them and invoke each element's Execute() method:
如果您不想使用现有的解决方案(例如 boost::function),则需要创建一个表示函数的基类,然后创建包装各种函数源的派生类。例如:
If you don't want to use an existing solution such as boost::function, you will need to create a base class that represents a function, and then derived classes that wrap various sources of functions. For example: