[comp.lang.c++] Generic Function Pointer Declarations

roger@zuken.co.jp (Roger Meunier) (03/06/91)

Lets' say that I have two modules A and B, where A knows classes in B
but B knows nothing about A.  However, B sometimes needs to notify A,
i.e., call a member function of an unknown class in A.  A could pass
the function pointer and class instance pointer to B for later use,
allowing B to call the registered function using the two pointers.

Using Glockenspiel 1.2, I used to be able to do the following:

----------------------  begin code frag  --------------------------
typedef	void	(*FuncType)(void*,int, int);	// in module B

class	Interface				// in module B
{
public:
	FuncType	func;
	void*		instance;

	void	SetFunc(FuncType f,void* i)
	{ func = f; instance = i; }
};

class	Test					// in module A
{
public:
	int	x,y;

	void	TestFunction(int,int);
};

void	Test::TestFunction(int a,int b)
{
	x = a;
	y = b;
}

main()
{
	Interface	interface;
	Test		test;

	interface.SetFunc(Test::TestFunction,&test); // register function in B
}
----------------------  end code frag  --------------------------

This would compile as is.  But using HP's version of AT&T's 2.0, I get the
following error:

CC: "func.C", line 33: error 1264: bad argument  1 type for Interface::SetFunc(): void (Test::*)(int , int ) ( FuncType  expected)

2.0 wants the function pointer declared as:

	typedef	void	(Test::*FuncType)(void*,int, int);

but module B doesn't know about "Test::", so the compiler can only be
satisfied if I cast as follows:

	interface.SetFunc((FuncType)Test::TestFunction,&test);

which shows me how sloppy my scheme is in the eyes of 2.0.

With all this in mind, I have two questions:

1)  Is there a way to define a function pointer to a C++ class member
function (other than a friend) without specifying the class name?

2)  Would the "best" way (in 2.0) to implement a "generic" interface between
highly independent modules be to define a "generic" class in B which will
become the base class for all classes in A which want to be called from B?
This would result in a function pointer definition like:

	typedef	void	(GenericIF::*FuncType)(void*,int, int);

and then classes in A would be defined like:

	class	Test: public GenericIF { ... };

[This seems like a lot of unnecessary work just to satisfy the language
requirements.]

Any feedback would be appreciated.
--
Roger Meunier @ Zuken, Inc.  Yokohama, Japan	(roger@zuken.co.jp)