// abstract base class
class Functor
{
public:
virtual void call(int i, string s) {};
};
template <class T>
class SpecificFunctor : public Functor
{
public:
SpecificFunctor(T* _object, void(T::*_callback)(int i, string s)) {
object = _object;
callback = _callback;
}
// overide
void call(int i, string s) {
(*object.*callback)(i, s);
}
private:
void (T::*callback)(int i, string s);
T* object;
};
As you can see I want to be able to point to any type of object. Every button will have a SpecificFunctor as a member, I think it's best to create it when I create the button and that leaves me with a constructor that looks like this:
template<class T>
Button::Button(WindowHandler *handler, WindowID id, T owner, void (*callback)(WindowID, std::string), int x, int y, int width, int height) {
mFunctor = new Functor(); // mFunctor is a member variable
SpecificFunctor<T> specific(&owner, &T::callback); // should it be T::callback instead?
mFunctor = &specific;
}
So when a button get's created it'll look like this:
Editor::Editor()
{
mWindowHandler = new WindowHandler();
Button<Editor> *button = new Button(mWindowHandler, TEST_BUTTON, this, &messageHandler, 500, 500, 40, 20);
}
There's two things I don't like about this.
1.) The syntax is clumsy, I would prefer that it looked like this when one create a button:
Button *button = new Button(mWindowHandler, TEST_BUTTON, &messageHandler, 500, 500, 40, 20); So the user only has to think about passing the right function, it doesn't seem that userfriendly to both pass the owner and the type of the owner.
2.) The fact that button actually will HAVE a editor. It really doesn't feel right.
So my question is,
Is this the way I must do it or is there some smarter or better way?