Re: Casting PointerToMemeberFunction
<mzaytsev2@bloomberg.net> wrote in message
news:1192025286.873892.239220@o80g2000hse.googlegroups.com...
I'm looking for the fastest way to dispatch events to member
functions.
I come up to solution like that:
class Binder {
public:
struct P {};
template < class T >
Binder( T* obj, void (T::*fptr)() )
: m_obj( reinterpret_cast< P* >( obj ) )
, m_fptr( static_cast< void (P::*)() >( fptr )
{}
void operator() () { ( m_obj->*m_fptr ) (); }
private:
P* m_obj;
void (P::*m_fptr)();
};
class Handler : public Binder::P
{
public:
void foo();
};
int main()
{
Handler h;
Binder b ( &h, &Handler::foo );
b();
};
It works, in real world (Sun CC, g++, MSVC).
I'm wondering should it work according to the standard.
{ clc++m banner removed - please remove it yourself -mod }
I'll let someone else answer the question as asked, but I'm just wondering
what's wrong with the more obvious solution:
#include <iostream>
template <typename T>
class Binder
{
private:
T *m_obj;
void (T::*m_func)();
public:
Binder(T *obj, void (T::*func)())
: m_obj(obj), m_func(func)
{}
void operator()()
{
(m_obj->*m_func)();
}
};
struct Handler
{
void foo()
{
std::cout << "foo()" << std::endl;
}
};
struct HandlerBase
{
virtual ~HandlerBase() {}
virtual void foo() = 0;
};
struct Handler1 : HandlerBase
{
void foo()
{
std::cout << "Handler1::foo()" << std::endl;
}
};
int main()
{
Handler h;
Binder<Handler> b(&h, &Handler::foo);
b();
Handler1 h1;
Binder<HandlerBase> bhb(&h1, &HandlerBase::foo);
bhb();
return 0;
}
In particular, if you want to be able to dispatch to different handlers,
just make them all inherit from the same base class (HandlerBase in the
above). Or are you trying to do something else?
Hope this helps :-)
Stu
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]