callbacks and classes

Started by
1 comment, last by Thex0 18 years ago
i want to add functions to an array to call them later. i know its not possible over different classes, except with static declarations i tested a little and got stuck ... it should be used for example as callbacks for actions in an inputsystem( for mouse and keyboard) compiler says he cant cast int testfunc"( int, char*)" into "somefunc (__cdecl *)" ... any suggestions ?

typedef int (somefunc)( int a, char *b);

class A {

public:
	
	somefunc *funcs[10];
	int counter;

	A() {

		memset( funcs, 0, sizeof( somefunc* ) * 10 );
		counter= 0;
	}


	void addAction( somefunc *func) {

		funcs[counter]= func;
		++counter;
	}


	void go() {

		for( int i= 0; i < counter; ++i ) {

			if( NULL != funcs ) {

				funcs( i, 0 );
			}
		}
	}
};


class B : public A {

public:

	int testfunc( int a, char *b ) {

		printf( "huhu %i\n", a );
		
		return 0;
	}

	B() : A() {

		addAction( testfunc );
		
	}
	

};

int main( int argc, char **args ) {


	B test;

      B.go();

	return 0;
}


Advertisement
testfunc is a member function, and these have special rules in c++. Specifically, the compiler silently makes it so that member functions recieve a hidden "this" pointer.

The syntax for pointer to member functions isnt pretty.

Here is a link that talks about it...

Note that if you had testfunc as a free floating function, or as a tatic function, you're code would probably work.

Good Luck!
You could try using the boost::function library with which you can mix function pointers with member function pointers :)´

If you just want the learning experience you could always write a functor of your own, it's not too much code for simple functors with low parameter counts, but it requires some template fiddling :)

This topic is closed to new replies.

Advertisement