I'm trying to implement an observer pattern (of sorts) with C++ and I want to use function pointer to do so, but I keep getting an error when trying to cast a function pointer from class B to a typedef function pointer:
#include <map>
typedef int (*OutputEvent)(const char*, const char*, int);
class A
{
private:
int nextListenerId;
std::map<int, OutputEvent> listenerMap;
public:
A(){ nextListenerId = 0;}
~A(){}
inline int RegisterListener(OutputEvent callback)
{
nextListenerId++;
listenerMap[nextListenerId] = callback;
return nextListenerId;
}
};
class B
{
private:
int listenerId;
public:
B(const A& a)
{
OutputEvent e = &B::CallMeBack;
listenerId = a.RegisterListener(e);
}
~B(){}
int CallMeBack(const char* x, const char* y, int z)
{
return 0;
}
};
I created this example and I've pasted it into codepad.org, but when I it fails to compile (it doesn't compile in codepad.org nor in Visual Studio 2010):
Output:
t.cpp: In constructor 'B::B(const A&)':
Line 28: error: cannot convert 'int (B::*)(const char*, const char*, int)' to 'int (*)(const char*, const char*, int)' in initialization
compilation terminated due to -Wfatal-errors.
I don't understand why it can't convert the function pointers. Could anybody help me please?