Skip to main content
gamedev.net
🔒 Locked

Pointer to member function?

Started by moagstar 1 reply 450+ views
Original Post
moagstar
moagstar
Hi, I'm trying to store a list of function pointers and at the moment it looks something a bit like this :


class MyClass
{
private:
	typedef float(*myFunc)(float a, float b);
	vector<myFunc> myFunctionPointers;
public:
	void fun()
	{
		for(unsigned char i=0;i<myFunctionPointers.size();i++)
		{
			myFunctionPointers(1.0f, 2.0f);
		}
	}

	void registerFunction(myFunc function)
	{
		myFunctionPointers.push_back(function);
	}
};




When I try to add a non-member function to the list it has no problems i.e.


float testFunction(float a, float b)
{
	return a*b;
}

int main()
{
	MyClass myInstance;

	myInstance.registerFunction(testFunction);

	return 0;
}



But when I try to add a member function of a class to the list, it doesn't like it

class MyOtherClass
{
private:
	MyClass myInstance;
public:
	float memberFunc(float a, float b)
	{
		return a*b;
	}

	MyOtherClass()
	{
		myInstance.registerFunction(memberFunc);
	}
};

I get the following error : error C2664: 'MyClass::registerFunction' : cannot convert parameter 1 from 'float (float,float)' to 'MyClass::myFunc' How can I get to accept this function as an argument to registerFunction? Thanks in advance!
civguy
civguy
Remember that member functions get "this" parameter implicitely. The signature of myFunc has no "this" parameter, so naturally you can't call a member function through myFunc.

For basics on member function pointers, see this.

For solution to your problem, see this and this and especially this
moagstar
moagstar
Thanks! Although I didn't find the boost so useful the information on function pointers was excellent, and has solved the problem!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.