I have an http server that has a request handler like that :
bool handleRequest(const RequestObject& request, ResponseRequest& response);
I’m trying to write a wrapper that would provide an API like that :
addRouteHandler(GET, "/foo/bar", handler);
With handler able to be either :
- a function :
bool handleFooBarRequest(const RequestObject& request, ResponseRequest& response); - a method on an existing object :
FooResourceInstance+bool FooResource::handleFooBarRequest(const RequestObject& request, ResponseRequest& response); - a static method of an object :
static bool FooResource::handleFooBarRequest(const RequestObject& request, ResponseRequest& response);
I insist : C++03 (gcc 4.1.2) and no Boost (the reason is NOT the point)
So far the techniques I have found either use Boost, C++11 or third-party code (http://www.codeproject.com/Articles/136799/Lightweight-Generic-C-Callbacks-or-Yet-Another-Del)
Use an interface and a derived template class. This technique is called “type erasure”.
You might want to use a shared_ptr or similar instead of auto_ptr, all depends on how you want to store these objects.
Edit:
you can write your own member function wrapper/closure/function object. Code would looks something like the following (I haven’t tried compiling it so there could be some errors):