
While working on assignments for the Computergraphics course I'm taking this semester I was missing signals and slots. Using Qt for the assignments is not possible (well actually I didn't ask explicitly whether I could use it), so I felt challenged to code the convenient things I'm so used to...
I knew that boost had some implementation of signals and slots that used templates but I had never actually taken a look at it. And I didn't want to, yet. I wanted to think about the problem myself first. Basically I came up with that a signal needs to be an object where as a slot may not have to be an object, but must also work as a member function. After a few iterations I came up with a header that now allows me to do the following:
#include "signal.h"
#include <iostream>
struct A
{
void operator()()
{
std::cout << "A::operator()" << std::endl;
}
void f()
{
std::cout << "A::f" << std::endl;
}
};
struct B
{
void operator()(int x)
{
std::cout << "B::operator() " << x << std::endl;
}
void f(int x)
{
std::cout << "B::f " << x << std::endl;
}
};
void g()
{
std::cout << "g" << std::endl;
}
void g(int x)
{
std::cout << "g " << x << std::endl;
}
int main()
{
A a;
Signal<> s;
s.connect(&a);
s.connect(&a, &A::f);
s.connect(&g);
s();
B b;
Signal<int> s2;
s2.connect(&b);
s2.connect(&b, &B::f);
s2.connect(&g);
s2(5);
return 0;
}
The output of that program is:
A::operator()
A::f
g
B::operator() 5
B::f 5
g 5
as you probably expected. Notice that
Now you probably want to see the code for Signal: