Modern C++ 11/14 – C# alike events

For a project of mine I needed a functionality like that found in C# events. Since my C++ is a bit rusty 🙂 I looked up some options and found this example which I edited to support variadic templates.

The original implementation(now modified with variadic templates) from: http://geekswithblogs.net/raccoon_tim/archive/2011/09/28/lambdas-and-events-in-c.aspx

template<typename… T1>
class Event
{
public:
typedef std::function<void(T1…)> Func;

public:
void Call(T1 …arg)
{
for (auto i = m_handlers.begin(); i != m_handlers.end(); i++)
{
(*i)(arg…);
}
}

void operator ()(T1 …arg)
{
Call(arg…);
}

Event& operator += (Func f)
{
if (typeid(f) != typeid(Func))
throw std::bad_function_call(“Error in type”);

m_handlers.push_back(f);
return *this;
}

Event& operator -= (Func f)
{
for (auto i = m_handlers.begin(); i != m_handlers.end(); i++)
{
if ((*i).target<void(T1)>() == f.target<void(T1)>())
{
m_handlers.erase(i);
break;
}
}

return *this;
}

private:
std::vector<Func> m_handlers;
};

 

To use the event class in you code:

Example 1 – Single parameter:

int stackValue = 200; Event<int> e; e += [=](int i) { printf( “%d\n”, i + stackValue ); }; e += [&](int i) { printf( “%d\n”, i + stackValue ); stackValue += 100; }; e += [&stackValue](int i) { printf( “%d\n”, i + stackValue ); }; e += [stackValue](int i) { printf( “%d\n”, i + stackValue ); }; e( 100 );

Example 2 – Multiple Parameters:
int stackValue = 200;
float stackValue2 = 12;
double stackValue3 = 200;
Event<int, float, double> e;
e += [=](int i, float j, double k) { printf(“%d\n”, i + stackValue + (int)j + (int)k); };
e += [&](int i, float j, double k) { printf(“%d\n”, i + stackValue + (int)j + (int)k); stackValue += 100; };
e += [&stackValue](int i, float j, double k) { printf(“%d\n”, i + stackValue + (int)j + (int)k); };
e += [stackValue](int i, float j, double k) { printf(“%d\n”, i + stackValue + (int)j + (int)k); };

e(100, stackValue2, 53);

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s