Click here to Skip to main content
15,886,110 members
Articles / Programming Languages / C++

Implementation of Delegates in C++ using Signal and Slot pattern

Rate me:
Please Sign up or sign in to vote.
3.73/5 (7 votes)
12 Sep 20042 min read 48.9K   770   31  
The article describes an efficient way to implement delegates in C++ using Signal and Slot pattern.
// cpp_slot.cpp : Defines the entry point for the console application.
//

#include <algorithm>
#include "stdafx.h"
#include "CppSlot.h"

using namespace std;

class MyModel
{
public:

	void modelChanged()
	{
		m_signal.emit_sig(1);		
	} 

	CppSignal1<int,int> m_signal;
};

class MyView
{
public:

	MyView()
		: m_slot(this,&MyView::onModelChanged)
	{}

	int onModelChanged(int i)
	{
		cout << "model changed:" << i << endl;
		return 1;
	}

	CppSlot1<MyView,int,int> m_slot;
};

class MyView1
{
public:

	MyView1()
		: m_slot(this,&MyView1::onModelChanged)
	{}

	int onModelChanged(int i)
	{
		cout << "model changed 1:" << i << endl;
		return 2;
	}

	CppSlot1<MyView1,int,int> m_slot;
};

class ResponseAccumulator
{
	
public:
	
	typedef int return_type;
	template <typename iterator>
	int operator () (iterator begin,iterator end)
	{
		int sum = 0;
		for(iterator it=begin; it!=end; ++it)
			sum+=*it;

		return sum;
	}
	 
};

int _tmain(int argc, _TCHAR* argv[])
{
	// create model conaining CppSignal
	MyModel model;
	// create view with CppSlot
	MyView view;

	// connect signal to slot
	model.m_signal.connect(&view.m_slot);
	model.modelChanged();

	// create another 2 views and connect it to the model
	MyView1* view1 = new MyView1();
	model.m_signal.connect(&view1->m_slot);

	// use ResponseAccumulator function object 
	// to collect responses from models
	int res = model.m_signal.emit_sig(3,ResponseAccumulator());
	cout << "sum of responses is " << res << endl;

	// now we can delete second model end it
	// automatically disconnect itself from the 
	// model
	delete view1;
	res = model.m_signal.emit_sig(3,ResponseAccumulator());
	cout << "new sum of responses is " << res << endl;

	return 0;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Canada Canada
Baranovsky Eduard has been a software developer for more then 10 years. He has an experence in image processing, computer graphics and distributed systems design.

Comments and Discussions