Jan
21

Deeper into the Rabbit Hole: C++ Function Pointers and Callbacks Jon Keon

C++

DISCLAIMER:

The code shown in this post is not 100% my own original work. It is instead derivative of Elbert Mai’s post on a CodeProject submission on C++ Callbacks which I have used in a previous post for my Windows framework. Link.

My changes are largely cosmetic in terms of formatting and naming in an effort to fully understand what Elbert is doing. I have also fixed some of the code to allow for compiling on MacOS without compiler errors in GCC due to some template issues and I also added the ability to have equality checks between two Functions.

This post is not intended to show that I am the author or originator of the idea but rather to delve deeper into how it works and how it can be used in projects.

Background:

When I first started playing around with making my Windows framework I had a rough idea of how I wanted it to work and it involved the use of Function objects as they are implemented in ActionScript 3.0.

Essentially for any function anywhere (including anonymous ones) you can store these in an object called Function, pass them around and invoke them at a later time.

//Assigns the doWork function to the myFunction variable
var myFunction:Function = myClass.doWork;
//Calls myClass.doWork
myFunction();

This works extremely well if you want to place these Function objects inside a Dictionary and Key them off of an integer or string. Since the Windows Messaging Pump works by sending different Messages, it would be great to use the Windows Message as the Key and a Function object as the value which can be invoked once the corresponding message is received.

Sadly this isn’t a native feature of C++. In my research I came across using raw function pointers but the specificity and syntax is complex and confusing and not an ideal path for a generic solution.

Raw function pointers are perfectly fine when you know exactly what type of function is going to be registered all the time… in which case, why not pass in a reference to the containing class and just call the function directly?

A general solution requires a feature of C++ called templates and that is a whole other can of worms that can be quite complex at first glance.

Fortunately I found Elbert Mai’s implementation of Callbacks on CodeProject.com and was able to simply use them.

I had looked at the code but it was overwhelming and it satisfied my needs for the time being.

After working more with C++ I was determined to go back and deconstruct the library, fully understand it, and if possible, improve upon it.

The results are a marginal improvement in that Functions can be equated although I’m sure there will be those that say they are not actually equal. For the intended purposes that I am using the Function class for, they are indeed equal and it works in all of my test cases. But nothing groundbreaking here.

The real benefit was that I am very familiar and comfortable with all types of Function pointers and in using Template programming with Template Partial Specialization. Learning++;

Function Pointers:

There are essentially two types of Function Pointers in C++. (There are technically more if you want to get really in depth, but essentially there are two ways of accessing them).

There is a great article on Code Project by Don Clugston that goes very in depth as to how Function Pointers work across different environments and Compilers here. He also gives an implementation of Callbacks like Elbert Mai as well.

The first type is a Free Function pointer which is any static or global function. (A function that does not require an instance of a class to be executed).

The syntax for a Free Function pointer is ugly though:

<Return Type> (*<Variable Name>)(<Parameter Type> <Parameter Name>);

Where:

<Return Type> is the type that the function returns. (void, int, etc)

<Variable Name> is the name you want to give your function pointer so you can reference it after.

<Parameter Type> is the type of parameter this function takes in.

<Parameter Name> is the name of the parameter this function takes in.

This can still be confusing so lets look at an example:

//Actual void Function that takes in an int
#include <iostream>
void TestFreeFunction(int p) {
	std::cout << "Value of P is " << p << std::endl;
}

//Declares a Free Function Pointer called freeFunctionPointer
//with return type void, and takes in one parameter that is an int
//and maps it to the Global function TestFreeFunction.
void (*freeFunctionPointer)(int parameter) = &TestFreeFunction;

Here we have a Global function called TestFreeFunction that takes in one parameter of type int and return nothing so it’s return type is void. We create a function pointer with return type of void, give it a name of freeFunctionPointer and then specify that it takes in one parameter of type int. We then assign the address of the Function to our Function Pointer variable.

To call the function we simply do the following:

//To use it, simply place brackets and pass in an int
(*freeFunctionPointer)(7);

The second type of Function Pointer is called a Member Function pointer. This function pointer requires an instance of a class to be used and complicates things a bit.

The syntax for a Member Function pointer is:

<Return Type> (<Class Type>::*<Variable Name>)(<Parameter Type> <Parameter Name>);

This is almost the same as the Free Function pointer but instead includes a <Class Type> which is the type of class the function pointer is a part of.

Again an example illustrates it best:

#include <iostream>
//Class with Member Function
class TestMemberFunctionClass {

public:
	//Actual Member Function with return type void and takes in one parameter of type int
	void TestMemberFunction(int p) {
		std::cout << "Value of P is " << p << std::endl;
	}
};

//Declares a Member Function Pointer called memberFunctionPointer
//with return type void, and takes in one parameter that is an int
//and with a ClassType of TestMemberFunctionClass
//and maps it to the Member Function in TestMemberClass
void (TestMemberFunctionClass::*memberFunctionPointer)(int parameter) = &TestMemberFunctionClass::TestMemberFunction;

Notice that we must specify the class qualifier when taking the address of the Function as well.

In order to call the function:

//We must have an instance of the class
TestMemberFunctionClass instance;
//To use it, invoke the function pointer on the instance
(instance.*memberFunctionPointer)(7);

Member Function pointers must have an instance specified in order to work. Member Function pointers do not point to specific functions on objects. Instead they point to specific functions on a Class Type. The instance qualifies which actual function to invoke.

The Problem:

So we have our two Function pointers. What’s the problem?

Well the problem lies in how specific the Function Pointers are and the fact that the vast majority of them will be Member Functions. Looking at our example Member Function pointer that function pointer is only valid for functions that return void, take in one and only one parameter that is an int and are part of the TestMemberFunctionClass.

Obviously this severely limits the usefulness of this variable.

To use only raw Function Pointers we’d have to declare one for every “type” of Function we might want to point to and do a giant switch statement. Something that is neither developer friendly nor performant.

Fortunately we have a solution in the usage of templates.

Templates:

Templates in C++ aren’t always shown in the best light due to the perception that they are complicated and make it difficult to read code.

I would agree with both of those statements. However, if you take the time to really dig into templates and understand how they work, they can be very powerful and aren’t as complex as they initially appear to be.

Let’s start with a very simple example:

//Templated Function that takes in some type and returns that same type.
template <typename ParamType>
ParamType TemplatedFunction(ParamType p) {
	return p;
}

This function uses the template keyword to specify that this function is a templated function and uses the typename ParamType to specify that ParamType could be anything. In short, it’s a definition or “template”.

This function will return something of type ParamType and takes in a variable of type ParamType.

Now initially we don’t know what this will be. But it could be anything.

As we write our code and use the function, the compiler will then properly build the real functions that we need.

For example:

int myInt = TemplatedFunction(6);
float myFloat = TemplatedFunction(12.2);

Will actually generate the following two functions even though we never wrote them ourselves. Note: The compiler generates these functions behind the scenes and doesn’t actually write C++ code.

//Compiler generated function for type int. (Not actually ever seen)
int TemplatedFunction(int p) {
	return p;
}
//Compiler generated function for type float. (Not actually ever seen)
float TemplatedFunction(float p) {
	return p;
}

As you can see, the type we needed to use in our code generated a function using that type. This example is very simple but if you can imagine taking this concept to that of Member Function pointers, you can see how it would be extremely useful. We can write our handlers just once and let the compiler create the proper actual functions to handle all the different possibilites we might pass into it.

This is in fact the basis of how many libraries for handling Callbacks or Delegates work.

First Attempts:

My first attempt was to just create a standalone Function object for each type of Function. (Free Function and Member Function) Both of these work and work quite well but I’ll get into the problems after when I revisit Elbert Mai’s solution and slightly modify it.

Free Function:

template <typename ReturnType>
class FreeFunction {

//PUBLIC FUNCTIONS
public:
	//Constructor - Set function pointer via initalizer list
	inline FreeFunction(ReturnType (*fp)()) : freeFunctionPointer(fp) {}

	//Copy Constructor - Set function pointer via initializer list
	inline FreeFunction(const FreeFunction& other) : freeFunctionPointer(other.freeFunctionPointer) {}

	//Destructor - Simply set function pointer to 0
	inline ~FreeFunction() {
		freeFunctionPointer = 0;
	}

	//Overloading () operator so we can use this like a Function
	inline ReturnType operator() () {
		return (*freeFunctionPointer)();
	}

	//Overloading = operator to allow for assignment
	inline FreeFunction<ReturnType>& operator= (const FreeFunction<ReturnType> &other) {
		if (*this != &other) {
			freeFunctionPointer = other.freeFunctionPointer;
		}
		return *this;
	}

	//Exposing private variables to global equality functions
	template <typename EqualFuncReturnType>
	friend inline bool operator== (const FreeFunction<EqualFuncReturnType> &lhs, const FreeFunction<EqualFuncReturnType> &rhs);
	template <typename NotEqualReturnType>
	friend inline bool operator!= (const FreeFunction<NotEqualReturnType> &lhs, const FreeFunction<NotEqualReturnType> &rhs);

//PRIVATE VARIABLES
private:
	//Stores a Free Function Pointer
	ReturnType (*freeFunctionPointer)();


};

//Global Equality Function
template <typename EqualFuncReturnType>
inline bool operator== (const FreeFunction<EqualFuncReturnType> &lhs, const FreeFunction<EqualFuncReturnType> &rhs) {
	return (lhs.freeFunctionPointer == rhs.freeFunctionPointer);
}

//Global InEquality Function
template <typename NotEqualReturnType>
inline bool operator!= (const FreeFunction<NotEqualReturnType> &lhs, const FreeFunction<NotEqualReturnType> &rhs) {
	return (lhs.freeFunctionPointer != rhs.freeFunctionPointer);
}

The FreeFunction class simply wraps a Free Function pointer and provides some convenient methods to invoke the function and check equality etc. In terms of templating, the only varying aspect is the return type as this version only supports functions that take in 0 parameters. (To handle multiple parameters we need to create multiple versions of the class as you will see later)

Equality functions are implemented as global functions that are friends of the class so they can inspect the private properties of the FreeFunction class.

Member Function:

template <typename ReturnType, class ClassType>
class MemberFunction {

//PUBLIC FUNCTIONS
public:
	//Constructor - Set function pointer via initalizer list
	inline MemberFunction(ReturnType (ClassType::*fp)(), ClassType *ip) : memberFunctionPointer(fp), instancePointer(ip) {}

	//Copy Constructor - Set function pointer via initializer list
	inline MemberFunction(const MemberFunction&; other) : memberFunctionPointer(other.memberFunctionPointer), instancePointer(other.instancePointer) {}

	//Destructor - Simply set function pointer and instance pointer to 0
	inline ~MemberFunction() {
		memberFunctionPointer = 0;
		instancePointer = 0;
	}

	//Overloading () operator so we can use this like a Function
	inline ReturnType operator() () {
		return (instancePointer->*memberFunctionPointer)();
	}

	//Overloading = operator to allow for assignment
	inline MemberFunction<ReturnType, ClassType>& operator= (const MemberFunction<ReturnType, ClassType> &other) {
		if (*this != &other) {
			memberFunctionPointer = other.memberFunctionPointer;
			instancePointer = other.instancePointer;
		}
		return *this;
	}

	//Exposing private variables to global equality functions
	template <typename EqualFuncReturnType, class EqualFuncClassType>
	friend inline bool operator== (const MemberFunction<EqualFuncReturnType, EqualFuncClassType> &lhs, const MemberFunction<EqualFuncReturnType, EqualFuncClassType> &rhs);
	template <typename NotEqualFuncReturnType, class NotEqualFuncClassType>
	friend inline bool operator!= (const MemberFunction<NotEqualFuncReturnType, NotEqualFuncClassType> &lhs, const MemberFunction<NotEqualFuncReturnType, NotEqualFuncClassType> &rhs);

//PRIVATE VARIABLES
private:
	//Stores a Member Function Pointer
	ReturnType (ClassType::*memberFunctionPointer)();
	//Stores an Instance Pointer
	ClassType *instancePointer;
};

//Global Equality Function
template <typename EqualFuncReturnType, class EqualFuncClassType>
inline bool operator== (const MemberFunction<EqualFuncReturnType, EqualFuncClassType> &lhs, const MemberFunction<EqualFuncReturnType, EqualFuncClassType> &rhs) {
	return ((lhs.instancePointer == rhs.instancePointer) && (lhs.memberFunctionPointer == rhs.memberFunctionPointer));
}

//Global InEquality Function
template <typename NotEqualFuncReturnType, class NotEqualFuncClassType>
inline bool operator!= (const MemberFunction<NotEqualFuncReturnType, NotEqualFuncClassType> &lhs, const MemberFunction<NotEqualFuncReturnType, NotEqualFuncClassType> &rhs) {
	return ((lhs.instancePointer != rhs.instancePointer) || (lhs.memberFunctionPointer != rhs.memberFunctionPointer));
}

Same thing here with the MemberFunction class. We wrap the member function pointer and store the instance pointer as well. Templating needs to be updated to include a class type. (You’ll notice that I use typename and class, there is no difference in what these keywords do but I differentiate by using typename when it’s a type that gets returned or passed in, and class when it’s explicitly referring to qualifying something like “ClassType::something”).

In addition the equality checks also include checking the instance pointers.

So both of these classes work very well but there are two issues.

  1. Declaring a Member Function Pointer requires you to specify the ClassType in the declaration of your Function Pointer.
  2. You can’t use both of them interchangeably. Ie. You can’t have a vector of FreeFunctions and MemberFunctions, only one or the other.

Elbert’s Solution:

As pointed out here, Elbert Mai came up with a great way to have one Function object that handles both Member and Free Functions.

I won’t fully go into it right now but the basic premise is that he used Partial Template Specialization with  Global Function to extract the Type information. He then creates a temporary Builder class with that type information. Using that Builder class, he invokes two partial template specialized static functions which create the actual Function object.

This Function object receives a Free Function pointer to the templated static function. NOT the actual function. The actual function exists as the partial template specialized parameter and gets invoked when the static function is invoked.

If you scratched your head and said “HUH?” don’t worry, you’re not alone. It took me a while to fully grasp this and understand how cool it actually is.

I’ll use my version of Elbert’s Solution to walkthrough it as it’s more verbosely commented and the names are expanded out to make it easier to read for learning.

My Take on Elbert’s Solution:

So the first thing we need to take a look at is the following code:

//Declaring a Class called Function which can be of any type. Naturally we want it to be the Function Signature.
//We're declaring this here so that the Type itself exists but does nothing and we can extend this with Partial Template Specialization later.
template <typename FunctionSignature>
class Function;

This simply declares the class called Function and that it can be templated with a Function Signature. We’re not going to implement the class in any way because we don’t actually want a generic version of the class. Instead we want partially specialized versions of the class to be generated only when needed and by the types of functions we’re going to use.

Next we’ll look at how it gets invoked from the member function perspective and follow the chain of execution.

It all starts with a helper Macro:

/Creates and Returns a Member Function object. Functions inside a class.
#define MEMBER_FUNCTION(functionPointer, instancePointer) util::CreateFunctionBuilder(functionPointer).Wrap<functionPointer>(instancePointer)

This Macro simply makes it easier for end users to create Member Function pointers. It takes in the function pointer address and a pointer to the class instance.

Note: This will error in Eclipse Indigo as Symbol ‘Wrap’ could not be resolved and Invalid arguments ‘Candidates are: util::Function<classtype ()>. These are known issues with Eclipse’s code analysis and can be ignored. GCC will compile it just fine. No issues on Visual Studio 2010

Usage is:

//Declares a Function of signature int(int, float) called mTestOne and maps it to MemberClass::TestMember on instance mem
util::Function<int (int, float)> mTestOne = MEMBER_FUNCTION(&MemberClass::TestMember, &mem);

This is fairly nice syntax. You specify a function and it’s templated type is the signature of the function. Then all you have to do is pass in the Function pointer address and a pointer to the instance.

You can even typedef your function type if you will be using it a lot or for even better readability.

typedef util::Function<int (int, float)> IntFunction;
IntFunction mTestOne = MEMBER_FUNCTION(&MemberClass::TestMember, &mem);

Let’s now look at the first part of the Macro, the CreateFunctionBuilder function.

//////////////////////////////////////////////////////////////////////
// GLOBAL FUNCTION CREATOR: MEMBER FUNCTION 2 PARAMETER VERSION //////
//////////////////////////////////////////////////////////////////////

template <typename ReturnType, class ClassType, typename Param0, typename Param1>
inline MemberFunctionBuilder2<ReturnType, ClassType, Param0, Param1> CreateFunctionBuilder(ReturnType (ClassType::*fp)(Param0 p0, Param1 p1)) {
	return MemberFunctionBuilder2<ReturnType, ClassType, Param0, Param1>();
}

Ok so now the eyes start to bleed a bit.
First off this is a template function and it expects to receive four parameters. One for the Return Type of the Function, one for the Class Type and one for each of the Parameters to be passed in.

The function will construct an instance of MemberFunctionBuilder2 with those four types based on what gets passed in.

If we use our function from the macro, the compiler will create a function line this:

//Not a real function, simply illustrating what the template expands too when compiled.
inline MemberFunctionBuilder2<int, MemberClass, int, float> CreateFunctionBuilder(int (MemberClass::*fp)(int p0, float p1)) {
	return MemberFunctionBuilder2<int, MemberClass, int, float>();
}

Ok this makes a bit more sense. There is now an actual function just for our specific Function pointer that returns an int and takes in an int and a float on an instance of a MemberClass.

Once this MemberFunctionBuilder2 instance is created we call the static method Wrap on it to create the actual Function object. To see how this works, let’s look at the MemberFunctionBuilder2 class.

//////////////////////////////////////////////////////////////////////
// FUNCTION BUILDER: MEMBER FUNCTION 2 PARAMETER VERSION /////////////
//////////////////////////////////////////////////////////////////////

//Builds a Member Function
template <typename ReturnType, class ClassType, typename Param0, typename Param1>
class MemberFunctionBuilder2 {
public:
	//Empty Constructor/Destructor
	inline MemberFunctionBuilder2() {}
	inline ~MemberFunctionBuilder2() {}

	//Performs the wrapping from the actual Member Function to the static Free Function Wrapper in this class. Casts the instance pointer to a const void*
	template<ReturnType (ClassType::*functionPointer)(Param0 p0, Param1 p1)>
	inline static Function<ReturnType (Param0, Param1)> Wrap(ClassType* ip) {
		return Function<ReturnType (Param0, Param1)>(&MemberFunctionBuilder2::template Wrapper<functionPointer>, static_cast<const void*>(ip));
	}

private:
	//Redirects to the functionPointer passed in at compile time via template params. Also casts the const void* back to the correct class instance.
	template<ReturnType (ClassType::*functionPointer)(Param0 p0, Param1 p1)>
	inline static ReturnType Wrapper(const void* ip, Param0 p0, Param1 p1) {
		ClassType* instancePointer = const_cast<ClassType*>(static_cast<const ClassType*>(ip));
		return (instancePointer->*functionPointer)(p0, p1);
	}

};

Ok back to bleeding eyes, the class itself is meaningless and will in fact get destroyed once the function calls from the macro return due to them going out of scope; but we need it because of it’s template parameters. These template parameters allow for us to define static functions that use those template parameters.
The Wrap function creates a new Function by combining the ReturnType and any ParamX template parameters into a Function Signature. This allows us to create a Function using our Function Signature as the specialization for that Function Class.

Essentially, we will have a Function class that specifically tuned to our specific type of Function Signature.

Let’s look at the Wrap function as it will be generated by the compiler:

//Not an actual function, just to illustrate what it expands too when compiled
//functionPointer gets populated by &amp;MemberClass::TestMember
inline static Function<int (int, float)> Wrap(MemberClass* ip) {
	return Function<int (int, float)>(&amp;MemberFunctionBuilder2::template Wrapper<functionPointer>, static_cast<const void*>(ip));
}

Again we see our Function Signature of return type int with two params int and float and we see that it also takes in a pointer to an instance of a MemberClass. This is because it’s still a Member Function pointer and in order to invoke it we need an instance of the class.

The Wrap function constructs a Function object (which we will see in a moment) but it doesn’t give the Function object itself the Function Pointer or even the Instance pointer. Remember at the beginning there are two types of Function pointers. Free and Member. Those two aren’t compatible and we can’t store them in one catch all variable. So instead we have to lose some information in the interest of storage and a common interface.

Instead of passing in the actual Raw Member Function pointer, we pass in a Free Function Pointer which points to the private static function called Wrapper which has been template specialized by the actual Raw Member Function pointer.

This is the whole trick and it’s really quite brilliant.

At compile time, we have a Static function that is specialized to our Function pointer’s signature so it is unique. Inside that Static function we’ve basically hardcoded the address to the actual Member Function Pointer via template specialization. We only pass the function pointer to the static function into the Actual Function object which is a Free Function pointer. So regardless of whether we originally wanted to fire off a Free Function or a Member Function, only a Free Function pointer needs to be stored.

When we go to invoke the stored function pointer in the Function object itself, it invokes the Static Wrapper function which in turn invokes either the Member Function or the Free Function we originally wanted to store. It’s simply a layer of indirection.

You’ll also notice that we are casting the instance pointer to a void*. There’s a lot of information on the net about how this can be a bad thing but for our purposes it’s fine. We simply need to store the instance value in a generic way in the Function object.

Let’s look at the Wrapper function now:

//Redirects to the functionPointer passed in at compile time via template params. Also casts the const void* back to the correct class instance.
template<ReturnType (ClassType::*functionPointer)(Param0 p0, Param1 p1)>
inline static ReturnType Wrapper(const void* ip, Param0 p0, Param1 p1) {
	ClassType* instancePointer = const_cast<ClassType*>(static_cast<const ClassType*>(ip));
	return (instancePointer->*functionPointer)(p0, p1);
}

This function is what gets sent to the Function object and later invoked when you want to call your function again. Again using template specialization it allows the original function to be called. Let’s take a look using our actual function parameters

//Not an actual function. Just illustrating how it expands.
inline static int Wrapper(const void* ip, int p0, float p1) {
	MemberClass* instancePointer = const_cast<MemberClass*>(static_cast<const MemberClass*>(ip));
	return (instancePointer->*functionPointer)(p0, p1);
}

This should be feeling fairly familiar now, the Wrapper function takes in a void* pointer representing the instance which we can cast back to the actual Class type because the template already knows what Class it should be. As well due to template specialization the actual function pointer itself is stored in the definition of the function and so we can invoke it on our instance pointer and pass in the two parameters.

Finally we can look at the actual Function class which really is just a shell that we can use to pass around in a more generic way.

//////////////////////////////////////////////////////////////////////
// FUNCTION: 2 PARAMETER VERSION /////////////////////////////////////
//////////////////////////////////////////////////////////////////////

//Using Template Partial Specialization we will only allow implementations of a Function class which are typed to be a Function that could have any return type.
template <typename ReturnType, typename Param0, typename Param1>
class Function<ReturnType (Param0, Param1)> {

//PUBLIC FUNCTIONS
public:
	//Default Constructor - To allow for creation with assigning
	inline Function() : functionPointer(0), instancePointer(0) {}

	//Constructor - Set function pointer via initalizer list
	inline Function(ReturnType (*fp)(const void*, Param0 p0, Param1 p1), const void *ip) : functionPointer(fp), instancePointer(ip) {}

	//Copy Constructor - Set function pointer via initializer list
	inline Function(const Function& other) : functionPointer(other.functionPointer), instancePointer(other.instancePointer) {}

	//Destructor - Simply set function and instance pointer to 0
	inline ~Function() {
		functionPointer = 0;
		instancePointer = 0;
	}

	//Overloading = operator to allow for assignment
	inline Function<ReturnType>& operator= (const Function<ReturnType> &other) {
		functionPointer = other.functionPointer;
		instancePointer = other.instancePointer;
		return *this;
	}

	//Overloading () operator so we can use this like a Function
	inline ReturnType operator() (Param0 p0, Param1 p1) const {
		return (*functionPointer)(instancePointer, p0, p1);
	}

	//Safe Bool Idiom - Allows for checking if a Function has a valid functionPointer or not.
	typedef const void* Function::*bool_type;
	inline operator bool_type() const {
		return (functionPointer != 0) ? &Function::instancePointer : false;
	}

	template <typename EqualFuncReturnType>
	friend inline bool operator ==(const Function<EqualFuncReturnType> & lhs, const Function<EqualFuncReturnType> & rhs);
	template<typename NotEqualFuncReturnType>
	friend inline bool operator !=(const Function<NotEqualFuncReturnType> & lhs, const Function<NotEqualFuncReturnType> & rhs);

//PRIVATE VARIABLES
private:
	//Stores a Free Function Pointer to the static wrapper function
	ReturnType (*functionPointer)(const void*, Param0 p0, Param1 p1);
	//Stores an Instance Pointer
	const void *instancePointer;

};

And we should look at it as well with the params filled in.

//Not an actual class, simply illustrating expansion when compiled
class Function<int (int, float)> {

//PUBLIC FUNCTIONS
public:
	//Default Constructor - To allow for creation with assigning
	inline Function() : functionPointer(0), instancePointer(0) {}

	//Constructor - Set function pointer via initalizer list
	inline Function(int (*fp)(const void*, int p0, float p1), const void *ip) : functionPointer(fp), instancePointer(ip) {}

	//Copy Constructor - Set function pointer via initializer list
	inline Function(const Function& other) : functionPointer(other.functionPointer), instancePointer(other.instancePointer) {}

	//Destructor - Simply set function and instance pointer to 0
	inline ~Function() {
		functionPointer = 0;
		instancePointer = 0;
	}

	//Overloading = operator to allow for assignment
	inline Function<int (int, float)>& operator= (const Function<int (int, float)> &other) {
		functionPointer = other.functionPointer;
		instancePointer = other.instancePointer;
		return *this;
	}

	//Overloading () operator so we can use this like a Function
	inline ReturnType operator() (int p0, float p1) const {
		return (*functionPointer)(instancePointer, p0, p1);
	}

	//Safe Bool Idiom - Allows for checking if a Function has a valid functionPointer or not.
	typedef const void* Function::*bool_type;
	inline operator bool_type() const {
		return (functionPointer != 0) ? &Function::instancePointer : false;
	}

	friend inline bool operator ==(const Function<int (int, float)> & lhs, const Function<int (int, float)> & rhs);
	friend inline bool operator !=(const Function<int (int, float)> & lhs, const Function<int (int, float)> & rhs);

//PRIVATE VARIABLES
private:
	//Stores a Free Function Pointer to the static wrapper function
	int (*functionPointer)(const void*, int p0, float p1);
	//Stores an Instance Pointer
	const void *instancePointer;

};

The class itself is fairly basic and the comments should explain most of it. Elbert’s version has a few more extra features that I’m not sure if I’ll add in to my version or not. I want to try and wait and see if they are needed.

The first thing to notice are the two pieces of member data. A Function pointer to a static function that matches our function signature. This will hold the static Wrapper function. And a const void* which will hold our casted instance. In the case of actual Free Functions, this will always be 0.

In terms of functions we have a Default Constructor so we can simply declare an empty Function and populate it later. A Constructor which takes in the Function Pointer and instance pointer, a Copy constructor which simply copies the two pointers and a Destructor which sets both pointers to 0. The Destructor doesn’t really need to set them to 0 since Function objects are always created on the Stack but I put it in all the same in case it ever goes on the Heap and I change how it works.

In terms of operators, the assignment operator is overloaded so we can assign Functions to Functions.

The most important operator is the () operator which lets us use the Function as a Function. It simply calls the Static Wrapper function and passes along whatever variables we need to pass.

Finally we have what is known as the Safe Bool Idiom which let’s us do something like if (myFunction) { but safely. I won’t go into details but it’s a good article to read.

The last part of the class is two friend declarations for the equality and inequality operators. This is the one major change I made to Elbert’s version because I definitely needed to have the ability to check if two Function objects were the same.

And that sums up how Functions work from start to finish.

There are just two more quick topics to discuss and then the final full source.

Parameter Versions:

You might have noticed that the comments refer to the code as the “2 Parameter Version”. The one thing we can’t do is write code once and have it work for a variable length of arguments so we have to duplicate a lot of the code to account for the different parameters. This is annoying but not a bad thing since C++ supports overloading of functions. Depending on what you pass in it will resolve to the proper function to handle X amount of Parameters. The version I’ll paste at the end only supports up to two parameters because otherwise the file is super long but you can easily extend it to as many parameters as you need. Commonly this is anywhere from 6 to 8. If you’re passing in more… well maybe you might want to condense some of those into a Data class to more easily pass around.

Equality:

The equality subject is a bit sticky because we’re kind of breaking the rules here. You are allowed to compare two function pointers for equality provided they are the same type. (Free or Member). You’re also allowed to compare any two pointers together because they are just pointers so we’re allowed to compare our instance pointers.

The problem arises in that if we compare the two function pointers in the Function object, we’re not actually comparing the Function pointers but actually comparing the Static Wrapper Function pointers instead.

This should immediately set off alarm bells in your head as it’s a static function so it’s very easy to have a one to many relationship resulting in false positives.

However; we’re also using template specialization keyed to our exact function signature. So there isn’t one static function everything gets piped through, instead there are many static functions that are uniquely tied to our original function pointers.

Since we’re really just looking for a way to check if the same function will be called, the comparison is still valid at the static wrapper level. I have tested this with various free functions, member function, virtual functions etc and the tests all properly come back as true when they are in fact equal and false when they are not.

I will admit that there may be a corner case here, but I have no found it and I’ve stepped through the debugger looking at the addresses and even started digging in the dissassembly. (But that’s a future post).

The great thing about the equality functions is we only need one set and not multiple versions for each parameter since templating will just create the versions we need. This allows us to add functions to maps and check if a function already exists in a set or not.

Conclusion:

Well this has been yet another novel, but the subject is deep and complex and I spent a lot of time digging into it to really understand how it all works and how I can use it in my own projects. Once again I have to thank Elbert Mai and Don Clougston for making their own discoveries and code available so I could piece it all together. I touched on some very interesting and complex areas of C++ and came out with more tools for the toolbox.

One final note with the below source, you’ll notice it handles a third function type known as a const Member function. This is the exact same as the Member Function it’s just const and unfortunately requires duplication of the code to make the compiler enforce your code properly.

At the end of the day, these Functions have a ton of benefits as outlined in Elberts article but one of the best is that it’s all resolved at compile time. If there are going to be errors, you’re going to get them before you’re running your program. In addition the compiler will optimize a lot for you, inlining function calls and making things fast.

Source:

/*********************************
*Class: Function
*Description: Based off of Elbert Mai's (http://www.codeproject.com/script/Membership/View.aspx?mid=2301380) implementation
*of Callbacks (http://www.codeproject.com/KB/cpp/CPPCallback.aspx).
*Modified to support equality and heavily commented to provide easier understanding of what's happening under the hood.
*Author: jkeon
**********************************/

#ifndef _FUNCTION_H_
#define _FUNCTION_H_

//////////////////////////////////////////////////////////////////////
// MACROS ////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

//Creates and Returns a Free Function object. Static functions etc.
#define FREE_FUNCTION(functionPointer) util::CreateFunctionBuilder(functionPointer).Wrap<functionPointer>()

//Creates and Returns a Member Function object. Functions inside a class.
#define MEMBER_FUNCTION(functionPointer, instancePointer) util::CreateFunctionBuilder(functionPointer).Wrap<functionPointer>(instancePointer)

//////////////////////////////////////////////////////////////////////
// NAMESPACE /////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////

namespace util {

	//////////////////////////////////////////////////////////////////////
	// CLASS DECLARATION /////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////

	//Declaring a Class called Function which can be of any type. Naturally we want it to be the Function Signature.
	//We're declaring this here so that the Type itself exists but does nothing and we can extend this with Partial Template Specialization later.
	template <typename FunctionSignature>
	class Function;


	//////////////////////////////////////////////////////////////////////
	// GLOBAL EQUALITY CHECKS ////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////

	template <typename EqualFuncReturnType>
	inline bool operator== (const Function<EqualFuncReturnType> &lhs, const Function<EqualFuncReturnType> &rhs) {
		return ((lhs.functionPointer == rhs.functionPointer) && (lhs.instancePointer == rhs.instancePointer));
	}

	template <typename NotEqualFuncReturnType>
	inline bool operator!= (const Function<NotEqualFuncReturnType> &lhs, const Function<NotEqualFuncReturnType> &rhs) {
		return ((lhs.functionPointer != rhs.functionPointer) || (lhs.instancePointer != rhs.instancePointer));
	}


	//*********************************************************************************************************************************************************************
	//*********************************************************************************************************************************************************************

	//////////////////////////////////////////////////////////////////////
	// FUNCTION: 0 PARAMETER VERSION /////////////////////////////////////
	//////////////////////////////////////////////////////////////////////

	//Using Template Partial Specialization we will only allow implementations of a Function class which are typed to be a Function that could have any return type.
	template <typename ReturnType>
	class Function<ReturnType ()> {

	//PUBLIC FUNCTIONS
	public:
		//Default Constructor - To allow for creation with assigning
		inline Function() : functionPointer(0), instancePointer(0) {}

		//Constructor - Set function pointer via initalizer list
		inline Function(ReturnType (*fp)(const void*), const void *ip) : functionPointer(fp), instancePointer(ip) {}

		//Copy Constructor - Set function pointer via initializer list
		inline Function(const Function& other) : functionPointer(other.functionPointer), instancePointer(other.instancePointer) {}

		//Destructor - Simply set function and instance pointer to 0
		inline ~Function() {
			functionPointer = 0;
			instancePointer = 0;
		}

		//Overloading = operator to allow for assignment
		inline Function<ReturnType>& operator= (const Function<ReturnType> &other) {
			functionPointer = other.functionPointer;
			instancePointer = other.instancePointer;
			return *this;
		}

		//Overloading () operator so we can use this like a Function
		inline ReturnType operator() () const {
			return (*functionPointer)(instancePointer);
		}

		//Safe Bool Idiom - Allows for checking if a Function has a valid functionPointer or not.
		typedef const void* Function::*bool_type;
		inline operator bool_type() const {
			return (functionPointer != 0) ? &Function::instancePointer : false;
		}

		//Allowing for Equality/InEquality Checks by granting the Global Equality/InEquality Check Functions access to this classes internals via the friend keyword.
		template <typename EqualFuncReturnType>
		friend inline bool operator ==(const Function<EqualFuncReturnType> & lhs, const Function<EqualFuncReturnType> & rhs);
		template<typename NotEqualFuncReturnType>
		friend inline bool operator !=(const Function<NotEqualFuncReturnType> & lhs, const Function<NotEqualFuncReturnType> & rhs);

	//PRIVATE VARIABLES
	private:
		//Stores a Free Function Pointer to the static wrapper function
		ReturnType (*functionPointer)(const void*);
		//Stores an Instance Pointer
		const void *instancePointer;

	};

	//////////////////////////////////////////////////////////////////////
	// FUNCTION BUILDER: FREE FUNCTION 0 PARAMETER VERSION ///////////////
	//////////////////////////////////////////////////////////////////////

	//Builds a Free Function
	template <typename ReturnType>
	class FreeFunctionBuilder0 {
	public:
		//Empty Constructor/Destructor
		inline FreeFunctionBuilder0() {}
		inline ~FreeFunctionBuilder0() {}

		//Performs the wrapping from the actual Free Function to the static Free Function Wrapper in this class.
		template<ReturnType (*functionPointer)()>
		inline static Function<ReturnType ()> Wrap() {
			return Function<ReturnType ()>(&FreeFunctionBuilder0::template Wrapper<functionPointer>, 0);
		}

	private:
		//Redirects to the functionPointer passed in at compile time via template params
		template<ReturnType (*functionPointer)()>
		inline static ReturnType Wrapper(const void*) {
			return (*functionPointer)();
		}
	};

	//////////////////////////////////////////////////////////////////////
	// FUNCTION BUILDER: MEMBER FUNCTION 0 PARAMETER VERSION /////////////
	//////////////////////////////////////////////////////////////////////

	//Builds a Member Function
	template <typename ReturnType, class ClassType>
	class MemberFunctionBuilder0 {
	public:
		//Empty Constructor/Destructor
		inline MemberFunctionBuilder0() {}
		inline ~MemberFunctionBuilder0() {}

		//Performs the wrapping from the actual Member Function to the static Free Function Wrapper in this class. Casts the instance pointer to a const void*
		template<ReturnType (ClassType::*functionPointer)()>
		inline static Function<ReturnType ()> Wrap(ClassType* ip) {
			return Function<ReturnType ()>(&MemberFunctionBuilder0::template Wrapper<functionPointer>, static_cast<const void*>(ip));
		}

	private:
		//Redirects to the functionPointer passed in at compile time via template params. Also casts the const void* back to the correct class instance.
		template<ReturnType (ClassType::*functionPointer)()>
		inline static ReturnType Wrapper(const void* ip) {
			ClassType* instancePointer = const_cast<ClassType*>(static_cast<const ClassType*>(ip));
			return (instancePointer->*functionPointer)();
		}

	};

	//////////////////////////////////////////////////////////////////////
	// FUNCTION BUILDER: CONST MEMBER FUNCTION 0 PARAMETER VERSION ///////
	//////////////////////////////////////////////////////////////////////

	//Builds a Const Member Function
	template <typename ReturnType, class ClassType>
	class ConstMemberFunctionBuilder0 {
	public:
		//Empty Constructor/Destructor
		inline ConstMemberFunctionBuilder0() {}
		inline ~ConstMemberFunctionBuilder0() {}

		//Performs the wrapping from the actual Const Member Function to the static Free Function Wrapper in this class. Casts the instance pointer to a const void*
		template<ReturnType (ClassType::*functionPointer)() const>
		inline static Function<ReturnType ()> Wrap(ClassType* ip) {
			return Function<ReturnType ()>(&ConstMemberFunctionBuilder0::template Wrapper<functionPointer>, static_cast<const void*>(ip));
		}

	private:
		//Redirects to the functionPointer passed in at compile time via template params. Also casts the const void* back to the correct class instance.
		template<ReturnType (ClassType::*functionPointer)() const>
		inline static ReturnType Wrapper(const void* ip) {
			ClassType* instancePointer = const_cast<ClassType*>(static_cast<const ClassType*>(ip));
			return (instancePointer->*functionPointer)();
		}

	};

	//////////////////////////////////////////////////////////////////////
	// GLOBAL FUNCTION CREATOR: FREE FUNCTION 0 PARAMETER VERSION ////////
	//////////////////////////////////////////////////////////////////////

	template <typename ReturnType>
	inline FreeFunctionBuilder0<ReturnType> CreateFunctionBuilder(ReturnType (*fp)()) {
		return FreeFunctionBuilder0<ReturnType>();
	}

	//////////////////////////////////////////////////////////////////////
	// GLOBAL FUNCTION CREATOR: MEMBER FUNCTION 0 PARAMETER VERSION //////
	//////////////////////////////////////////////////////////////////////

	template <typename ReturnType, class ClassType>
	inline MemberFunctionBuilder0<ReturnType, ClassType> CreateFunctionBuilder(ReturnType (ClassType::*fp)()) {
		return MemberFunctionBuilder0<ReturnType, ClassType>();
	}

	//////////////////////////////////////////////////////////////////////
	// GLOBAL FUNCTION CREATOR: C MEMBER FUNCTION 0 PARAMETER VERSION ////
	//////////////////////////////////////////////////////////////////////

	template <typename ReturnType, class ClassType>
	inline ConstMemberFunctionBuilder0<ReturnType, ClassType> CreateFunctionBuilder(ReturnType (ClassType::*fp)() const) {
		return ConstMemberFunctionBuilder0<ReturnType, ClassType>();
	}

	//*********************************************************************************************************************************************************************
	//*********************************************************************************************************************************************************************

	//////////////////////////////////////////////////////////////////////
	// FUNCTION: 1 PARAMETER VERSION /////////////////////////////////////
	//////////////////////////////////////////////////////////////////////

	//Using Template Partial Specialization we will only allow implementations of a Function class which are typed to be a Function that could have any return type.
	template <typename ReturnType, typename Param0>
	class Function<ReturnType (Param0)> {

	//PUBLIC FUNCTIONS
	public:
		//Default Constructor - To allow for creation with assigning
		inline Function() : functionPointer(0), instancePointer(0) {}

		//Constructor - Set function pointer via initalizer list
		inline Function(ReturnType (*fp)(const void*, Param0 p0), const void *ip) : functionPointer(fp), instancePointer(ip) {}

		//Copy Constructor - Set function pointer via initializer list
		inline Function(const Function& other) : functionPointer(other.functionPointer), instancePointer(other.instancePointer) {}

		//Destructor - Simply set function and instance pointer to 0
		inline ~Function() {
			functionPointer = 0;
			instancePointer = 0;
		}

		//Overloading = operator to allow for assignment
		inline Function<ReturnType>& operator= (const Function<ReturnType> &other) {
			functionPointer = other.functionPointer;
			instancePointer = other.instancePointer;
			return *this;
		}

		//Overloading () operator so we can use this like a Function
		inline ReturnType operator() (Param0 p0) const {
			return (*functionPointer)(instancePointer, p0);
		}

		//Safe Bool Idiom - Allows for checking if a Function has a valid functionPointer or not.
		typedef const void* Function::*bool_type;
		inline operator bool_type() const {
			return (functionPointer != 0) ? &Function::instancePointer : false;
		}

		//Allowing for Equality/InEquality Checks by granting the Global Equality/InEquality Check Functions access to this classes internals via the friend keyword.
		template <typename EqualFuncReturnType>
		friend inline bool operator ==(const Function<EqualFuncReturnType> & lhs, const Function<EqualFuncReturnType> & rhs);
		template<typename NotEqualFuncReturnType>
		friend inline bool operator !=(const Function<NotEqualFuncReturnType> & lhs, const Function<NotEqualFuncReturnType> & rhs);

	//PRIVATE VARIABLES
	private:
		//Stores a Free Function Pointer to the static wrapper function
		ReturnType (*functionPointer)(const void*, Param0 p0);
		//Stores an Instance Pointer
		const void *instancePointer;

	};

	//////////////////////////////////////////////////////////////////////
	// FUNCTION BUILDER: FREE FUNCTION 1 PARAMETER VERSION ///////////////
	//////////////////////////////////////////////////////////////////////

	//Builds a Free Function
	template <typename ReturnType, typename Param0>
	class FreeFunctionBuilder1 {
	public:
		//Empty Constructor/Destructor
		inline FreeFunctionBuilder1() {}
		inline ~FreeFunctionBuilder1() {}

		//Performs the wrapping from the actual Free Function to the static Free Function Wrapper in this class.
		template<ReturnType (*functionPointer)(Param0 p0)>
		inline static Function<ReturnType (Param0)> Wrap() {
			return Function<ReturnType (Param0)>(&FreeFunctionBuilder1::template Wrapper<functionPointer>, 0);
		}

	private:
		//Redirects to the functionPointer passed in at compile time via template params
		template<ReturnType (*functionPointer)(Param0 p0)>
		inline static ReturnType Wrapper(const void*, Param0 p0) {
			return (*functionPointer)(p0);
		}
	};

	//////////////////////////////////////////////////////////////////////
	// FUNCTION BUILDER: MEMBER FUNCTION 1 PARAMETER VERSION /////////////
	//////////////////////////////////////////////////////////////////////

	//Builds a Member Function
	template <typename ReturnType, class ClassType, typename Param0>
	class MemberFunctionBuilder1 {
	public:
		//Empty Constructor/Destructor
		inline MemberFunctionBuilder1() {}
		inline ~MemberFunctionBuilder1() {}

		//Performs the wrapping from the actual Member Function to the static Free Function Wrapper in this class. Casts the instance pointer to a const void*
		template<ReturnType (ClassType::*functionPointer)(Param0 p0)>
		inline static Function<ReturnType (Param0)> Wrap(ClassType* ip) {
			return Function<ReturnType (Param0)>(&MemberFunctionBuilder1::template Wrapper<functionPointer>, static_cast<const void*>(ip));
		}

	private:
		//Redirects to the functionPointer passed in at compile time via template params. Also casts the const void* back to the correct class instance.
		template<ReturnType (ClassType::*functionPointer)(Param0 p0)>
		inline static ReturnType Wrapper(const void* ip, Param0 p0) {
			ClassType* instancePointer = const_cast<ClassType*>(static_cast<const ClassType*>(ip));
			return (instancePointer->*functionPointer)(p0);
		}

	};

	//////////////////////////////////////////////////////////////////////
	// FUNCTION BUILDER: CONST MEMBER FUNCTION 1 PARAMETER VERSION ///////
	//////////////////////////////////////////////////////////////////////

	//Builds a Const Member Function
	template <typename ReturnType, class ClassType, typename Param0>
	class ConstMemberFunctionBuilder1 {
	public:
		//Empty Constructor/Destructor
		inline ConstMemberFunctionBuilder1() {}
		inline ~ConstMemberFunctionBuilder1() {}

		//Performs the wrapping from the actual Const Member Function to the static Free Function Wrapper in this class. Casts the instance pointer to a const void*
		template<ReturnType (ClassType::*functionPointer)(Param0 p0) const>
		inline static Function<ReturnType (Param0 p0)> Wrap(ClassType* ip) {
			return Function<ReturnType (Param0 p0)>(&ConstMemberFunctionBuilder1::template Wrapper<functionPointer>, static_cast<const void*>(ip));
		}

	private:
		//Redirects to the functionPointer passed in at compile time via template params. Also casts the const void* back to the correct class instance.
		template<ReturnType (ClassType::*functionPointer)(Param0 p0) const>
		inline static ReturnType Wrapper(const void* ip, Param0 p0) {
			ClassType* instancePointer = const_cast<ClassType*>(static_cast<const ClassType*>(ip));
			return (instancePointer->*functionPointer)(p0);
		}

	};

	//////////////////////////////////////////////////////////////////////
	// GLOBAL FUNCTION CREATOR: FREE FUNCTION 1 PARAMETER VERSION ////////
	//////////////////////////////////////////////////////////////////////

	template <typename ReturnType, typename Param0>
	inline FreeFunctionBuilder1<ReturnType, Param0> CreateFunctionBuilder(ReturnType (*fp)(Param0 p0)) {
		return FreeFunctionBuilder1<ReturnType, Param0>();
	}

	//////////////////////////////////////////////////////////////////////
	// GLOBAL FUNCTION CREATOR: MEMBER FUNCTION 1 PARAMETER VERSION //////
	//////////////////////////////////////////////////////////////////////

	template <typename ReturnType, class ClassType, typename Param0>
	inline MemberFunctionBuilder1<ReturnType, ClassType, Param0> CreateFunctionBuilder(ReturnType (ClassType::*fp)(Param0 p0)) {
		return MemberFunctionBuilder1<ReturnType, ClassType, Param0>();
	}

	//////////////////////////////////////////////////////////////////////
	// GLOBAL FUNCTION CREATOR: C MEMBER FUNCTION 1 PARAMETER VERSION ////
	//////////////////////////////////////////////////////////////////////

	template <typename ReturnType, class ClassType, typename Param0>
	inline ConstMemberFunctionBuilder1<ReturnType, ClassType, Param0> CreateFunctionBuilder(ReturnType (ClassType::*fp)(Param0 p0) const) {
		return ConstMemberFunctionBuilder1<ReturnType, ClassType, Param0>();
	}






	//*********************************************************************************************************************************************************************
	//*********************************************************************************************************************************************************************

	//////////////////////////////////////////////////////////////////////
	// FUNCTION: 2 PARAMETER VERSION /////////////////////////////////////
	//////////////////////////////////////////////////////////////////////

	//Using Template Partial Specialization we will only allow implementations of a Function class which are typed to be a Function that could have any return type.
	template <typename ReturnType, typename Param0, typename Param1>
	class Function<ReturnType (Param0, Param1)> {

	//PUBLIC FUNCTIONS
	public:
		//Default Constructor - To allow for creation with assigning
		inline Function() : functionPointer(0), instancePointer(0) {}

		//Constructor - Set function pointer via initalizer list
		inline Function(ReturnType (*fp)(const void*, Param0 p0, Param1 p1), const void *ip) : functionPointer(fp), instancePointer(ip) {}

		//Copy Constructor - Set function pointer via initializer list
		inline Function(const Function& other) : functionPointer(other.functionPointer), instancePointer(other.instancePointer) {}

		//Destructor - Simply set function and instance pointer to 0
		inline ~Function() {
			functionPointer = 0;
			instancePointer = 0;
		}

		//Overloading = operator to allow for assignment
		inline Function<ReturnType>& operator= (const Function<ReturnType> &other) {
			functionPointer = other.functionPointer;
			instancePointer = other.instancePointer;
			return *this;
		}

		//Overloading () operator so we can use this like a Function
		inline ReturnType operator() (Param0 p0, Param1 p1) const {
			return (*functionPointer)(instancePointer, p0, p1);
		}

		//Safe Bool Idiom - Allows for checking if a Function has a valid functionPointer or not.
		typedef const void* Function::*bool_type;
		inline operator bool_type() const {
			return (functionPointer != 0) ? &Function::instancePointer : false;
		}

		template <typename EqualFuncReturnType>
		friend inline bool operator ==(const Function<EqualFuncReturnType> & lhs, const Function<EqualFuncReturnType> & rhs);
		template<typename NotEqualFuncReturnType>
		friend inline bool operator !=(const Function<NotEqualFuncReturnType> & lhs, const Function<NotEqualFuncReturnType> & rhs);

	//PRIVATE VARIABLES
	private:
		//Stores a Free Function Pointer to the static wrapper function
		ReturnType (*functionPointer)(const void*, Param0 p0, Param1 p1);
		//Stores an Instance Pointer
		const void *instancePointer;

	};

	//////////////////////////////////////////////////////////////////////
	// FUNCTION BUILDER: FREE FUNCTION 2 PARAMETER VERSION ///////////////
	//////////////////////////////////////////////////////////////////////

	//Builds a Free Function
	template <typename ReturnType, typename Param0, typename Param1>
	class FreeFunctionBuilder2 {
	public:
		//Empty Constructor/Destructor
		inline FreeFunctionBuilder2() {}
		inline ~FreeFunctionBuilder2() {}

		//Performs the wrapping from the actual Free Function to the static Free Function Wrapper in this class.
		template<ReturnType (*functionPointer)(Param0 p0, Param1 p1)>
		inline static Function<ReturnType (Param0, Param1)> Wrap() {
			return Function<ReturnType (Param0, Param1)>(&FreeFunctionBuilder2::template Wrapper<functionPointer>, 0);
		}

	private:
		//Redirects to the functionPointer passed in at compile time via template params
		template<ReturnType (*functionPointer)(Param0 p0, Param1 p1)>
		inline static ReturnType Wrapper(const void*, Param0 p0, Param1 p1) {
			return (*functionPointer)(p0, p1);
		}
	};

	//////////////////////////////////////////////////////////////////////
	// FUNCTION BUILDER: MEMBER FUNCTION 2 PARAMETER VERSION /////////////
	//////////////////////////////////////////////////////////////////////

	//Builds a Member Function
	template <typename ReturnType, class ClassType, typename Param0, typename Param1>
	class MemberFunctionBuilder2 {
	public:
		//Empty Constructor/Destructor
		inline MemberFunctionBuilder2() {}
		inline ~MemberFunctionBuilder2() {}

		//Performs the wrapping from the actual Member Function to the static Free Function Wrapper in this class. Casts the instance pointer to a const void*
		template<ReturnType (ClassType::*functionPointer)(Param0 p0, Param1 p1)>
		inline static Function<ReturnType (Param0, Param1)> Wrap(ClassType* ip) {
			return Function<ReturnType (Param0, Param1)>(&MemberFunctionBuilder2::template Wrapper<functionPointer>, static_cast<const void*>(ip));
		}

	private:
		//Redirects to the functionPointer passed in at compile time via template params. Also casts the const void* back to the correct class instance.
		template<ReturnType (ClassType::*functionPointer)(Param0 p0, Param1 p1)>
		inline static ReturnType Wrapper(const void* ip, Param0 p0, Param1 p1) {
			ClassType* instancePointer = const_cast<ClassType*>(static_cast<const ClassType*>(ip));
			return (instancePointer->*functionPointer)(p0, p1);
		}

	};

	//////////////////////////////////////////////////////////////////////
	// FUNCTION BUILDER: CONST MEMBER FUNCTION 2 PARAMETER VERSION ///////
	//////////////////////////////////////////////////////////////////////

	//Builds a Const Member Function
	template <typename ReturnType, class ClassType, typename Param0, typename Param1>
	class ConstMemberFunctionBuilder2 {
	public:
		//Empty Constructor/Destructor
		inline ConstMemberFunctionBuilder2() {}
		inline ~ConstMemberFunctionBuilder2() {}

		//Performs the wrapping from the actual Const Member Function to the static Free Function Wrapper in this class. Casts the instance pointer to a const void*
		template<ReturnType (ClassType::*functionPointer)(Param0 p0, Param0 p1) const>
		inline static Function<ReturnType (Param0 p0, Param1 p1)> Wrap(ClassType* ip) {
			return Function<ReturnType (Param0 p0, Param1 p1)>(&ConstMemberFunctionBuilder2::template Wrapper<functionPointer>, static_cast<const void*>(ip));
		}

	private:
		//Redirects to the functionPointer passed in at compile time via template params. Also casts the const void* back to the correct class instance.
		template<ReturnType (ClassType::*functionPointer)(Param0 p0, Param1 p1) const>
		inline static ReturnType Wrapper(const void* ip, Param0 p0, Param1 p1) {
			ClassType* instancePointer = const_cast<ClassType*>(static_cast<const ClassType*>(ip));
			return (instancePointer->*functionPointer)(p0, p1);
		}

	};

	//////////////////////////////////////////////////////////////////////
	// GLOBAL FUNCTION CREATOR: FREE FUNCTION 2 PARAMETER VERSION ////////
	//////////////////////////////////////////////////////////////////////

	template <typename ReturnType, typename Param0, typename Param1>
	inline FreeFunctionBuilder2<ReturnType, Param0, Param1> CreateFunctionBuilder(ReturnType (*fp)(Param0 p0, Param1 p1)) {
		return FreeFunctionBuilder2<ReturnType, Param0, Param1>();
	}

	//////////////////////////////////////////////////////////////////////
	// GLOBAL FUNCTION CREATOR: MEMBER FUNCTION 2 PARAMETER VERSION //////
	//////////////////////////////////////////////////////////////////////

	template <typename ReturnType, class ClassType, typename Param0, typename Param1>
	inline MemberFunctionBuilder2<ReturnType, ClassType, Param0, Param1> CreateFunctionBuilder(ReturnType (ClassType::*fp)(Param0 p0, Param1 p1)) {
		return MemberFunctionBuilder2<ReturnType, ClassType, Param0, Param1>();
	}

	//////////////////////////////////////////////////////////////////////
	// GLOBAL FUNCTION CREATOR: C MEMBER FUNCTION 2 PARAMETER VERSION ////
	//////////////////////////////////////////////////////////////////////

	template <typename ReturnType, class ClassType, typename Param0, typename Param1>
	inline ConstMemberFunctionBuilder2<ReturnType, ClassType, Param0, Param1> CreateFunctionBuilder(ReturnType (ClassType::*fp)(Param0 p0, Param1 p1) const) {
		return ConstMemberFunctionBuilder2<ReturnType, ClassType, Param0, Param1>();
	}
}
#endif

This entry was posted on Saturday, January 21st, 2012 at 11:04 am and is filed under C++. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.