Original Post
I'm am just playing around with some code(below) that implements a windows callback function as a class. Basically how is works is that the class contains a templated static member function where the template arguemnts is only integers. This integer is so that the compiler creates a new function for each instance of the class. A preprocessor macro named Init which contains VC++ __COUNTER__ creates a unique(hopefully) integer for each instance. The macro maps to a class member function Init that saves the address of the templated static member function as a key in a <map> to the object pointer. So when the callback functions in entered it uses the address function to extract the object pointer from the <map> What I like to know is there a way to remove the dependence of #define Init() Init<__COUNTER__>() and if the implementation sound?
#include <iostream>
#include <map>
#define CALLBACK __stdcall
using namespace std;
typedef int UNIT;
typedef int HWND;
typedef int WPARAM;
typedef int LPARAM;
typedef int LRESULT;
typedef LRESULT (*WNDPROC)(HWND,UNIT,WPARAM,LPARAM);
class A{
public:
A():proc(NULL){};
operator WNDPROC()
{
return proc;
};
virtual LRESULT fn2(HWND z,UNIT y,WPARAM x,LPARAM w) {
cout << "Class A " << "fn2 "<<(int)this << endl;
return 0;
};
template<int T> void Init(void)
{
proc = WndProc<T>;
disp[proc] = this;
};
private:
template <int T> static LRESULT WndProc(HWND z,UNIT y,WPARAM x,LPARAM w)
{
A * a = disp[WndProc<T>];
return a->fn2(z,y,x,w);
};
private:
WNDPROC proc;
static map<WNDPROC,A *> disp;
};
map<WNDPROC,A *> A::disp;
class C : public A
{
public:
virtual LRESULT fn2(HWND z,UNIT y,WPARAM x,LPARAM w) {
cout << "Class C " << "fn2 "<<(int)this << endl;
return 0;
};
};
#define Init() Init<__COUNTER__>()
int main(int argc, char* argv[])
{
A a;
a.Init();
C b;
b.Init();
A * d = &b;
WNDPROC c = a;
c(0,0,0,0);
c = b;
c(0,0,0,0);
c = *d;
c(0,0,0,0);
return 0;
}