I know there are several out there, but I didn't like things about them. They just weren't right for what I needed: simple, powerful, reliable events for my objects. I've named my implementation ObjectEvents.
If there's interest I'll post my source later.
If there's interest I'll post my source later.
Code:
///////////////////////////////////////
// Complete sample of ObjectEvents
///////////////////////////////////////
#include <iostream>
#include "ObjectEvents.h"
typedef ObjectEvents::Delegate<int (class A* object, int& i, const int& ci)> ComplexDelegate; // not used below, but allowed
typedef ObjectEvents::Delegate<void (int number)> NumberDelegate;
typedef ObjectEvents::Delegate<void ()> EmptyDelegate;
class A
{
public:
NumberDelegate NumberEvent;
EmptyDelegate EmptyEvent;
// raises the NumberEvent event
void OnNumberEvent( int number ) { if ( NumberEvent ) NumberEvent( number ); }
// raises the EmptyEvent event
void OnEmptyEvent( ) { if ( EmptyEvent ) EmptyEvent( ); }
};
class B
{
public:
B(int v) : val(v) {}
static void function1()
{
std::cout << "In static B::function1" << std::endl;
}
void mfunction1()
{
std::cout << "In B::mfunction1: val is " << val << std::endl;
}
void mfunction2(int number)
{
std::cout << "In B::mfunction2: val is " << val << " number is " << number << std::endl;
}
private:
int val;
};
void Global(int number)
{
std::cout << "In Global: number is " << number << std::endl;
}
void main()
{
A a;
B b1(1);
B b2(2);
/////////////////////////
// hooking events
/////////////////////////
a.NumberEvent += NumberDelegate( Global );
a.NumberEvent += NumberDelegate( &b1, &B::mfunction2 );
a.NumberEvent += NumberDelegate( &b2, &B::mfunction2 );
// a.NumberEvent += EmptyDelegate( &b2, &B::mfunction1 ); // error
// a.NumberEvent += NumberDelegate( &b2, &B::mfunction1 ); // error
a.EmptyEvent += EmptyDelegate( &B::function1 );
EmptyDelegate del( &B1, &B::mfunction1 );
del += EmptyDelegate( &B2, &B::mfunction1 );
a.EmptyEvent += del;
// a.EmptyEvent += EmptyEvent( Global ); // error
// a.EmptyEvent += NumberDelegate( &B::function1 ); // error
// a.EmptyEvent += EmptyDelegate( &b2, &B::mfunction2 ); // error
/////////////////////////
// raising events
/////////////////////////
a.OnEmptyEvent();
a.OnNumberEvent(5);
a.OnNumberEvent(9);
/////////////////////////
// unhooking events
/////////////////////////
a.EmptyEvent -= EmptyDelegate( &B1, &B::mfunction1 );
a.OnEmptyEvent();
}
/////////////////////////
// Output
/////////////////////////
// In static B::function1
// In B::mfunction1: val is 1
// In B::mfunction1: val is 2
// In Global: number is 5
// In B::mfunction2: val is 1 number is 5
// In B::mfunction2: val is 2 number is 5
// In Global: number is 9
// In B::mfunction2: val is 1 number is 9
// In B::mfunction2: val is 2 number is 9
// In static B::function1
// In B::mfunction1: val is 2