c ++ super easy to use callback signal slot

Copyright: original articles without consent, is prohibited reprint https://blog.csdn.net/zmlovelx/article/details/82686123

Used Qt should know, signal slot, used for decoupling and callback super easy to use, if there is no Qt how to do, can be achieved using the function c ++ 11,

Of course there have been many implementations on the network can be directly used.

such as:

https://github.com/pbhogan/Signals

Sample code:

// Using Delegate.h

void MyFunc( int x )
{
	printf( "MyFunc( %d )", x );
}


// Using Signal.h

class Button
{	
public:
	Signal2< int, float > updateLabel;

	void Click( void )
	{
		updateLabel( 2, 34.5 );
	}
};

class Label
{
public:
	virtual void Update( int i, float f )
	{
		printf( "Update( %d, %.1f )", i, f );
	}
};

int main()
{
	Delegate1< int > delegate;
	delegate.Bind( & MyFunc );
	delegate( 5 );

	Button myButton;
	Label myLabel1;
	Label myLabel2;
	myButton.updateLabel.Connect( & myLabel1, & Label::Update );
	myButton.updateLabel.Connect( & myLabel2, & Label::Update );
	myButton.Click();

	return 0;
}

Is not very convenient, other projects:

https://github.com/NoAvailableAlias/nano-signal-slot

http://libsigc.sourceforge.net/

http://sigslot.sourceforge.net/

In fact, here there is a demand, like qt, like, you can specify a callback bound to the sender or reciver threads to execute this code where you need to call a callback to change the implementation, described simply looked down, as if this is not achieved several top function. there is also a self-threaded execution, finally achieved in this way is relatively simple.

Author: handsome too afraid to go c ++ Haha Church: 31,843,264

Guess you like

Origin blog.csdn.net/zmlovelx/article/details/82686123