Skip to main content
GameDev.net gamedev.net
🔒 Locked

Function Pointers

Started by Liam M Sep 21, 2005 at 8:29 AM 1 replies 600+ views
Original Post
Liam M
Liam M
When I first learnt C++ and encountered function pointers, it was one of those things I decided were fairly useful but too dificult for me as a newb to understand. Over the past few days though, I have gone back and learnt the in's and out's of the syntax and how FP's work. However, I have encountered a problem. Lets say we have a pointer, pX, which points to a function, fY. fY takes a single argument, an int. Is it possible, to set the arguments which are passed to fY when pX is initialised so that pY can be called without the need to specifically pass the aguments when it is called using pX? Il demonstrate what i mean:


int M; //This is what we want to be passed to fY whenever it is called through pX 
int  fY(int Z);//Our function itself.
int (*pX)(int) = fY(M);//pX is initialised to fY with the argument M




pX();//call  fY through pX, meaning that M is passed as an argument



Of course the above code doesnt work, but you get the idea of what im trying to achieve. And I'm not even sure if such a thing is possible to do. However, if it isn't, I would much appreciate suggestions for a work-around, or a way I can emulate this.
Enigma
Enigma
In C++ it is possible to write code that would allow you to do this. In fact some people have already done this for you and produced Boost.Function and Boost.Bind:
#include <boost/bind.hpp>#include <boost/function.hpp>int function(int Z){	return Z + 2;}int main(){	int M = 42;	// bind the value of M as an argument to function	boost::function0< int > functionPointer1 = boost::bind(function, M);	// bind M itself as an argument to function	boost::function0< int > functionPointer2 = boost::bind(function, boost::ref(M));	M = 1337;	// equivalent to function(42);	functionPointer1();	// equivalent to function(M);	functionPointer2();}

Enigma
Liam M
Liam M
Ahh, hit it on the head Enigma! Thank you very much, that works very nicely. Rate++!

Topic Locked

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

Sign in to reply to this topic.