Mr. Cluey : How To ...? : Function Pointers


How do I pass a function to a function?

Is there a way to pass in as a parameter to a function, the name of a method which gets called inside that function?

Yes - you use the "reference operator". See Appendix E of the 4Test Language Reference ("Comparison of 4Test and C") for details.

Tested Sample Code

window CustomWin theWindow
{
	Foo ()
	{
		print ("Foo called") ;
	}
	
	Bar ()
	{
		print ("Bar called") ;
	}
	
	Do ( string Verb )
	{
		@(Verb) () ;
	}
}

SomeFunction ( string AnyMethod )
{
	theWindow.@(AnyMethod)() ;
}

main ()
{
	theWindow.Do("Foo") ;	
	theWindow.Do("Bar") ;
	
	SomeFunction("Foo") ;	
	SomeFunction("Bar") ;
}

The function referenced by the variable doesn't have to be a method of an object - it can point to a regular function as well. If you pass the member function of an object, it will need an object to work with as well. And of course, you need to know the function arguments, or put together a mechanism for translating a varargs list into function parameters, perhaps like:

//Untested code - writing from memory...
SomeFunction ( string AnyMethod, varargs listArgs )
{
	select ListCount( listArgs )
	{
		case 0 : theWindow.@(AnyMethod)();
		case 1 : theWindow.@(AnyMethod)(listArgs[1]);
		case 2 : theWindow.@(AnyMethod)(listArgs[1],listArgs[2]); 
	}
}

See also Function References for more details.


Mr. Cluey : How To ...? : Function Pointers

Return to ATS Automated Testing Resources Page