The signal/slot mechanism is widely used in libjingle (using the sigslot library written by Sarah Thompson ).
Sigslot separates the previously called functions to a certain extent, and then freely binds (CONNECT) or disconnect) their call relationships during the program running. In this way, they are relatively loosely separated, but there is still a certain degree of coupling, such as the type and number of parameters of signal and slot must be consistent.
For example, the following line of code in relayserver:
- Void relayserver: addinternalsocket (talk_base: asyncpacketsocket * socket ){
- ...
- Socket-> signalreadpacket. Connect (this, & relayserver: oninternalpacket );
- }
After adding a UDP socket for internal connection, call signalreadpacket Of The UDP socket and call oninternalpacket () of the relayserver () (its definition is a common member function like relayserver, but the parameter must be consistent with the associated signal, and relayserver must inherit has_slots <>. In this way, when signalreadpacket is executed, oninternalpacket () is automatically called ().
Signal definition:
- Class asyncpacketsocket ...{
- Public:
- ...
- // Emitted each time a packet is read.
- Sigslot: signal4 <const char *, size_t, const socketaddress &, asyncpacketsocket *> signalreadpacket;
- ...
- }
Slot definition:
- Class relayserver: Public sigslot: has_slots <> {
- ...
- PRIVATE:
- ...
- Void oninternalpacket (
- Const char * bytes, size_t size, const talk_base: socketaddress & remote_addr,
- Talk_base: asyncpacketsocket * socket );
- ...
- }
Note:
The above oninternalpacket () is defined as private in the relayserver class, and can be executed outside the relayserver class through the signal/slot mechanism. This is determined by the use of function pointers in the sigslot library. It seems that C ++'s permission protection for private members is broken. Of course, this is authorized inside the slot class (relayserver: addinternalsocket (); so it can be said that the slot class knows that its private slot method will be executed outside the class, is informed and authorized. From this perspective, we can say that flexibility is provided: authorization can be executed, and private methods cannot be directly called without authorization.
-Qianli