简体   繁体   中英

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

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 . Maybe some other libraries will be more convenient/helpful, eg, boost.lambda (I didn't try it).

The std::mem_fun does the same trick as Vlad pointed. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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