Object-Oriented Callbacks for C++?(C++ 的面向对象回调?)
问题描述
是否有一些库可以让我在 C++ 中轻松方便地创建面向对象的回调?
Is there some library that allows me to easily and conveniently create Object-Oriented callbacks in c++?
例如,Eiffel 语言具有代理"的概念,其工作方式或多或少是这样的:
the language Eiffel for example has the concept of "agents" which more or less work like this:
class Foo{
public:
Bar* bar;
Foo(){
bar = new Bar();
bar->publisher.extend(agent say(?,"Hi from Foo!", ?));
bar->invokeCallback();
}
say(string strA, string strB, int number){
print(strA + " " + strB + " " + number.out);
}
}
class Bar{
public:
ActionSequence<string, int> publisher;
Bar(){}
invokeCallback(){
publisher.call("Hi from Bar!", 3);
}
}
输出将是:你好,来自酒吧!3 来自 Foo 的你好!
output will be: Hi from Bar! 3 Hi from Foo!
所以 - 代理允许将成员函数封装到一个对象中,给它一些预定义的调用参数(来自 Foo 的 Hi),指定开放参数(?),并将其传递给其他一些可以调用它的对象稍后.
So - the agent allows to to capsule a memberfunction into an object, give it along some predefined calling parameters (Hi from Foo), specify the open parameters (?), and pass it to some other object which can then invoke it later.
由于 c++ 不允许在非静态成员函数上创建函数指针,因此在 c++ 中实现一些易于使用的东西似乎并不容易.我在 google 上找到了一些关于 C++ 中面向对象回调的文章,但是,实际上我正在寻找一些库或头文件,我可以简单地导入它们,以便我使用一些类似的优雅语法.
Since c++ doesn't allow to create function pointers on non-static member functions, it seems not that trivial to implement something as easy to use in c++. i found some articles with google on object oriented callbacks in c++, however, actually i'm looking for some library or header files i simply can import which allow me to use some similarily elegant syntax.
有人对我有什么建议吗?
Anyone has some tips for me?
谢谢!
推荐答案
在 C++ 中使用回调最面向对象的方式是调用接口的函数,然后传递该接口的实现.
The most OO way to use Callbacks in C++ is to call a function of an interface and then pass an implementation of that interface.
#include <iostream>
class Interface
{
public:
virtual void callback() = 0;
};
class Impl : public Interface
{
public:
virtual void callback() { std::cout << "Hi from Impl
"; }
};
class User
{
public:
User(Interface& newCallback) : myCallback(newCallback) { }
void DoSomething() { myCallback.callback(); }
private:
Interface& myCallback;
};
int main()
{
Impl cb;
User user(cb);
user.DoSomething();
}
这篇关于C++ 的面向对象回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 的面向对象回调?
基础教程推荐
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 从 std::cin 读取密码 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01