Tuesday, July 6, 2010

QubLib Function Pointers

So, this post actually comes from some things I jotted down a while ago at 2:00 AM when I couldn't sleep. Hopefully it makes sense.

It's about 2:00 AM and I can't sleep because I'm pretty sure this idea is keeping me up. It's not really that new of an idea. I'm pretty sure that sigc++ has already done it, however I think QubLib needs to have some sort of Functor object, or an object that encapsulates a function pointer. This would make function pointer usage EXTREMELY easier, and I really think it would open the door for Delegates (at least what I think delegates are). My idea of a delegate is a function pointer that points to a function of a specific instance of a class. Now, having delegates brings up the question of what happens when you have a delegate pointing at an object that has gone out of Scope? I'm still working on a pretty way to solve that problem, but the syntax that I'm thinking of is below:

int add(int num1, int num2);

// The three template types are a return value, the type
// for arg1, and the type for arg2.
FunctionPointer a(&add);
a(5,3); // returns 5

class A {
void Do();

A aObj;
// With a delegate, the first value is the type of the
// class that the instance will be. Then the same
// rules as above remain constant.
Delegate d(&aObj, &A::Do);
d(); // This will call aObj.Do()

I also think that with a system like this in place, Events would become not only possible, but much easier. In my mind, an Event would be an object that called a bunch of other functions, similar to signal/slot ideas in Qt. For example, if an object had an Event called Changed, and everything the object's internal data changed it would call the Changed Event, any object or function pointer that had registered with my object's Changed Event would have their registered function called. Internally the Event would just be a list of FunctionPointer objects. One of the keys would be that there would be an IFunctionPointer interface that had only two method declarations: the () operator and the Execute() method. The signatures would be correctly typed through templates, so the compile-time type checker would ensure that correct function pointers were assigned to correct Events. Also, with the interface in place, you could have a normal function and a method of a specific object register with the same Event, because they would both implement the same interface. I'm excited to work on this one.

No comments:

Post a Comment