I have class which handles packages:
typedef void (*FCPackageHandlerFunction)(FCPackage*);
class FCPackageHandlers{
...
void registerHandler(FCPackage::Type type, FCPackageHandlerFunction handler);
void handle(FCPackage* package);
...
QHash<FCPackage::Type, FCPackageHandlerFunction> _handlers;
};
Then I have a server class who receive packages. Now I want to register a function who handles the packages. But this function must have a instance of the server for other variables.
So i try this:
struct FCLoginHandler{
FCServer* server;
FCLoginHandler(FCServer* server){
this->server = server;
}
void operator()(FCPackage* package){
std::cout << "Received package: " << package->toString().data() << "\n";
}
};
...
FCServer::FCServer(){
_handlers.registerHandle(FCPackage::Login, FCLoginHandler(this));
}
But then I get this error:
error: no matching function for call to 'FCPackageHandlers::registerHandler(FCPackage::Type, FCLoginHandler)'
note: candidates are: void FCPackageHandlers::registerHandler(FCPackage::Type, void (*)(FCPackage*))
Does anybody know the right solution?
You are trying to store a function object in a function pointer, and that’s not possible. You should store a
std::tr1::functioninstead:There’s a similar
functionclass in Boost in case you don’t have access to std::tr1 yet.Also, consider using
boost::bindand a regular function to avoid the boilerplate of having to create your own function objects such asFCLoginHandler:std::tr1::bindis also available in Boost, and if you don’t have access to that either you can always usestd::bind2nd.EDIT: Since you can’t modify the type of
FCPackageHandlerFunction, your best shot might be to add another hash that stores data associated to each function pointer:Presumably this is how you’ll have to implement
FCPackageHandlers::handle: