A
A
antonyter2012-11-26 13:07:14
linux
antonyter, 2012-11-26 13:07:14

What is the best way to pass Callback to an object?

There is a GUI implementation in pure C++03 without STL, Boost. It has a window->element->...->element hierarchy. One of the GUI elements is the Button. Events OnTapDown and others come to it.
The first option to organize a Callback was a function pointer. The disadvantage is that it is not possible to pass a class function. I had to fence a bunch of static methods, and even save a pointer to an object of the handler class.
The second option (never implemented) were interfaces with the necessary functions. But then we would have to fence objects to process each of the buttons.
The third option is now implemented - passing a functor containing a pointer to an object and a pointer to a class function. Example:

typedef BaseFunctor<void, const iPoint&> ButtonCallBackFunctor

mSomeButton->SetOnTap(ButtonCallBackFunctor::Create(this, &SomeClass::SomeClassFunction));

Moreover, the functor itself is implemented by the author on templates - a very heavy code turned out to be understandable.
Any ideas how this can be done better?

Answer the question

In order to leave comments, you need to log in

6 answer(s)
B
Biga, 2012-11-26
@antonyter

www.codeproject.com/Articles/7150/Member-Function-Pointers-and-the-Fastest-Possible

T
Talyutin, 2012-11-26
@Talyutin

Instead of your own functor implementation, use boost::function
www.boost.org/doc/libs/1_52_0/libs/bind/bind.html#with_boost_function

T
Talyutin, 2012-11-26
@Talyutin

C++0x already has it, what compiler version do you have?
The new C++ and even without stl is tough...

M
mejedi, 2012-11-26
@mejedi

The third option is now implemented - passing a functor containing a pointer to an object and a pointer to a class function.

Normal option.

L
leclecovich, 2012-11-26
@leclecovich

For my needs, I did it as follows: I added the ICallable interface with the only OneMethod () method. In the method that calls the callback method, I pass as arguments a pointer to the class that implements ICallable, as well as a pointer to the implemented interface method. It looks something like this:

void invokeCallback(void (ICallable::* pMethodPointer)(), ICallable *pInstance)
{
(pCalleeInstance->*pMethodPointer)();
}

The invokeCallback call looks like this:
ICallable *pImpl = new CallableImplementationClass();
invokeCallback(&ICallable::onlyOneMethod, pImpl);

As a result, we have the ability to call a callback method of an instance class.

N
nephrael, 2012-12-01
@nephrael

Look towards the Poco library:
in particular, the implementation of events
(start with Firing events, the last topic in the document)
pocoproject.org/slides/090-NotificationsEvents.pdf
besides, the code is ported to Android.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question