Reputation: 68114
I'm trying to pass a function from a derived class to a base class function which expects a function pointer, but I'm getting a compiler error.
[BCC32 Error] E2034 Cannot convert 'void (Bar::*)(int)' to 'void (Foo::*)(int)'
I guess this is as designed, but is there a way around this that doesn't involve unpleasant casting? Can boost::bind
help me here?
#define CALL_MEMBER_FN(object,ptrToMember) ((object).*(ptrToMember))
class Foo
{
public:
typedef void (Foo::*FFunc)(int i);
void test(FFunc f)
{
CALL_MEMBER_FN(*this,f)(123);
}
void barf1(int i) {};
};
class Bar : public Foo
{
public:
void barf2(int i) {};
};
void ffff()
{
Foo f;
f.test(Foo::barf1); // works
Bar b;
b.test(Bar::barf1); // works
b.test(Bar::barf2); // ERROR
}
As a side note, I have this working fine using a virtual function, which is the obvious approach rather than a function pointer, but I'm just trying to get it working this way before attempting some boost::bind trickery later...
Upvotes: 2
Views: 822
Reputation: 648
Can you generalise the function pointer a bit more? I mean something like this:
typedef void (Foo::*FFunc)(int i);
to:
typedef void (*FFunc)(int i);
Then you can use bind:
b.test(bind(&Bar::barf2, &b));
Upvotes: 1
Reputation: 12557
As well, as my knowledge of c++11 && bost && stl are not the best, I can only advise this:
template <typename T>
void test(void (T::*f)(int))
{
CALL_MEMBER_FN(static_cast<T&>(*this),f)(123);
}
All other code same to yours.
Bad casting, but it is hidden
Upvotes: 1
Reputation: 3918
b.test( ( Foo::FFunc )&Bar::barf2 );
Sorry, didn't mean to submit it as answer, wanted to comment. Sample code.
EDIT: Well, maybe this is more "pleasant" casting, since it's C++ style? Updated sample.
b.test( static_cast< Foo::FFunc >(&Bar::barf2) );
Upvotes: 1