hmm after a quick bit of research, I've found you can't actually do this, then I found a whole bunch of stuff I NEVER wanted to know about pointer-to-member-functions (i.e. depending on platform, inheritance, virtual-ity, etc they can be anywhere from 4 to 16 bytes!)
Happily there is a way around this. before I show you the code, I'll briefly explain the pros and cons of my method
Pros:
- it's way more flexible. you can pass ANY method of a class, even ones that require arguemetns.
cons:
- it requires boost::bind. you should have this installed anyway, so view this as an oppurtunity.
- it's a little more complicated
- there's a slight runtime cost.
Code:
#include <boost/bind.hpp>
class FBase
{
};
template <typename FUNC>
class functor : public FBase
{
public:
functor(FUNC f)
: m_f(f)
{}
void operator()(void)
{
m_f();
}
private:
FUNC m_f;
};
template <typename FUNC>
functor<FUNC> make_functor(FUNC f)
{
return functor<FUNC>(f);
}
class CBase
{
public:
void Register(FBase &f);
};
class CSub : public CBase
{
public:
void Method1();
void Method2();
void Method3();
};
int main()
{
CSub sub;
sub.Register(make_functor(boost::bind(CSub::Method1, sub)));
}
obviously that's not complete. there are memory leaks and so on, that you need to fix, but I'll leave that as an exercise for the reader (always wanted to say that )