Reputation: 233
I have two classes; class A notifies class B about some events.
typedef void (*callbackb) (B *, int param1);
class A
{
callbackb callme;
B *parent;
};
class B
{
A ai;
void set_cb() { ai.callme = cb_handler; }
static void cb_handler (B *obj, int param1) { obj->real_handler(param1); }
void real_handler(int param1);
};
There are two equivalent declarations, callbackb and cb_handler, but one of them is a function pointer, and other one is a function. Is it possible to change one or both, so that both were linked to single prototype declaration?
Upvotes: 2
Views: 67
Reputation: 170044
You can't define cb_handler
like you want. But you certainly can declare them based off the same prototype and have the compiler check it. It also stops you from hiding pointer semantics, which is a good thing. Here's how:
Define the callback as a function type:
typedef void callbackb(B *, int param1);
Declare the pointer and static member in terms of the CB type:
class A
{
callbackb *callme; // The pointer is explicit
B *parent;
};
// Later
class B
{
// ...
static inline callbackb cb_handler; // This is a function declaration
};
// And this is the inline definition, you can put it in a header
inline void B::cb_handler (B *obj, int param1) { obj->real_handler(param1); }
So now cb_handler
and callme
are declared in terms of the same type. You need to specify the complete prototype when defining cb_handler
, but it can still be an inline
out-of-class definition in a header.
The compiler will check that the definition of cb_handler
matches the declaration, so you'll be notified if cb_handler
differs from callbackb
.
Upvotes: 1