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++ 的面向对象回调?
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
