Monday, January 23, 2012

Evil C++ #5: Member function pointer special

Function pointers are one of the most esoteric and misunderstood features of C, and little was done in C++ to improve that situation (until C++11). I recently came to appreciate the peculiar evil of member function pointers in C++.

Friend of mine has a class, call it Foo, with a member function, call it threadMe. When constructed, Foo should create a new pthreads-like thread running threadMe, which will have access to this Foo's members.

That's all I know. Maybe there's a way to refactor it, but this is inside a tangle of library GUI code, which is always a mess (especially when that library is ROOT), and it's academically interesting.

Phase 0: Introduction
Before thinking about this, I had to refresh my memory on function pointers. Here is a simple example:

Even the somewhat arcane (*pointer)(args,args) syntax isn't not so bad. You're clearly dereferencing a pointer to a function.

Phase 1: Denial
The extension from the above globally-scoped functions to class member functions seems obvious. If the member is static, I should be able to do this:

int (*pStaticMemberFunction)(int);
pStaticMemberFunction = &(Foo::threadMe);

(Full program here). In C++, static member functions behave exactly like non-member functions.

For a non-static member function, one would reasonably expect the following syntax (full program):

  Foo* o = new Foo;
  int (*pMemberFunction)(int);
  pMemberFunction = &(o->threadMe);

NOPE. This isn't valid:

  error: ISO C++ forbids taking the address of a bound
  member function to form a pointer to member function.
  Say ‘&Foo::threadMe’ 

But... but... compiler. I don't want any Foo's threadMe. I want o's threadMe. Of course, if you foolishly follow GCC's advice anyway, hoping for some kind of magic, no. Just no.

  error: invalid use of non-static member function
  ‘int Foo::threadMe(int)’

Saw that one coming.

It appears that the &(object->memberFunction) syntax was actually considered for C++ at one point, as described in this heartbreaking 1994 article in the "Callbacks Using Template Functors" section. But in the end, this feature was deemed too complicated for the language and the compilation thereof, and left for libraries to implement. Some have, notably Boost.

Phase 2: Bad Hacks
There appears to be no general solution to the above problem, which is more than a syntactic issue, but has deep roots in the language's representation of function pointers. To proceed, I clearly need a pointer to a function with external linkage. The goal is to use such a function as a proxy: somehow, I call it and it calls the real (non-static member) function for me.

Bad Hack #1: Inadvisable Casting: The C++ FAQ strongly discourages casting a function pointer to a void pointer, but such a cast could allow me to construct a static wrapper function which would take an instance and a cleverly disguised member function pointer as an argument, solving the problem. At least for me, this casting works. However, there is no way to cast the void* back to a member function pointer that you could actually use. If C++ supported rvalue references, you could do something like

(void*) fnPtr = voidPtrArgument;

and perhaps get away with it, but it would be really evil C++. At any rate, it doesn't work.

Bad Hack #2: The Class With Incredible Foresight / Sledgehammer Approach: Another bad option is to create a mysterious superclass with virtual member functions having a wide variety of prototypes. For each of these prototypes, you can use a typedef to create a type meaning "pointer to a function like this one," e.g.

typedef int (SuperClass::*pSuperClassMemFnTakesIntReturnsInt)(int);
typedef void (SuperClass::*pSuperClassMemFnTakesIntReturnsVoid)(int);

Then, for each of these types, create a global launcher function, like

void* launchMember(SuperClass* o, pSuperClassMemFnTakesIntReturnsInt p)

Rather unwieldy. But, with this vast library of types, you can do whatever you want. Subclass "SuperClass" and implement member functions of your choosing, then call

launchMember(superClassInstance, &SuperClass::whateverFunction)

with abandon. A example "solving" the original problem is here.

Bad Hack #3: One Member Function to Rule Them All: The least kludgy option, I think. Sacrifice some generality and pick one exact function prototype (name and all), which will the the thready one. Then you can at least use the launcher for any class that has that prototype. This is cheating: the global launcher function doesn't take an instance and a member function pointer, it just takes an instance and we "know" which function to call.

A working example can be found here. This approach was partly inspired by this thread.

Phase 3: The Solution, But You Won't Like It
The best, most general solution is to change the language, which they just did in the new C++11 standard. The biggest deal is the introduction of a proper native threading library. Lambda functions also provide the abstraction needed to make creating threads with ad-hoc functions pretty slick. In all its glory:

This is great if you're running GCC >= 4.6. Otherwise, I guess Bad Hack #3 is probably best. If anyone else has better ideas, let me know in the comments!

No comments:

Post a Comment