简体   繁体   English

C ++,回调,对象和最佳实践

[英]C++, callbacks, objects and best practice

I'm looking for a solution to my problem. 我正在寻找解决我的问题的方法。 I found a workaround but I feel there should be a prettier way of doing this. 我找到了解决方法,但我认为应该有一种更漂亮的方法。 Here's my problem: I have an IPC library written in C. When message is received, it calls a callback function. 这是我的问题:我有一个用C编写的IPC库。收到消息后,它将调用回调函数。 I made a wrapper class on this library. 我在这个库上做了一个包装器类。 When the message is received, the wrapper class should trigger a signal (I'm using Qt yes). 收到消息后,包装器类应触发一个信号(我使用的是Qt yes)。 As you know, member function can't be a callback, so in my case, I wrote that callback outside the class. 如您所知,成员函数不能是回调,因此在我的情况下,我在类外部编写了该回调。 Now I have to emit a signal from the callback function, the only way I know is to make a public method for the wrapper class which will emit the signal, but I don't want to have that method public, and I can't access protected/private members outside the class. 现在我必须从回调函数中发出信号,我知道的唯一方法是为包装器类创建一个公共方法,该方法将发出信号,但是我不想将该方法公开,因此我不能访问课外的受保护/私人成员。 Anyone had similar problem? 有人有类似的问题吗? How did you solve that? 您是如何解决的?

Thanks 谢谢

如果希望成员函数为“回调”,则可以在类中将该函数声明为“静态”。

You can declare your outside funktion as a friend of that class and therefore wont need to make the method public. 您可以将外部函数声明为该类的朋友,因此无需将该方法公开。

Here a link to a tutorial. 这里是教程的链接

Postet as an answer as requested in comments. 按照评论的要求将Postet作为答案。

Well, a member function can be a callback, with some additional work. 好吧,成员函数可以是回调,还有一些其他工作。 This is something which is called "delegate". 这就是所谓的“委托”。 You could try boost::bind / boost::mem_fn . 您可以尝试boost::bind / boost::mem_fn Maybe some other libraries will be more convenient/helpful, eg, boost.lambda (I didn't try it). 也许其他一些库会更方便/有用,例如boost.lambda (我没有尝试过)。

The std::mem_fun does the same trick as Vlad pointed. std :: mem_fun与Vlad指出的技巧相同。 Making friends considered not a good design, since you are exposing all your class internals to be potentially accessible without even calling a member. 交朋友被认为不是一个好的设计,因为您公开了所有类的内部组件,甚至都没有给成员打电话就可以访问。

Static method will not be able to emit a singal, but it can access another static member pointing to your class. 静态方法将无法发出单数,但是它可以访问指向您的类的另一个静态成员。 You could create a special "caller" class that way, storing a single static pointer to your Qt object. 您可以通过这种方式创建一个特殊的“调用程序”类,并存储指向您的Qt对象的单个静态指针。

You could have a global class pointer, but it's even worse than having a friend. 您可以有一个全局类指针,但是它比拥有一个朋友还要糟糕。 You could make your class singleton, but it is similar to global variable in its tradeoffs, so doesn't worth it just for one use. 您可以使类成为单例,但它的权衡取舍类似于全局变量,因此不值得一用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM