I am studying how to implement simple delegates with c++11. The problem the disconnect-method, I would like to target specific function of specific object to be removed from the map. With this implementation, i erase all functions connected to specific object instance. Id like to be able to do something like :
delegate.disconnect (myobj, &MyObj::method)
instead of
delegate.disconnect (myobj)
which erases all connceted functions for myobj.
template <typename ... Params >
class Delegate {
private:
typedef std::function < void (Params...)> FunctionType;
std::map < void*, std::vector < FunctionType >> m_functions;
public:
template <typename Class>
void connect(Class& obj, void (Class::*func) (Params...) )
{
std::function < void (Class, Params...) > f = func;
FunctionType fun = [&obj, f](Params... params) { f(obj, params...); };
m_functions[&obj].push_back(fun);
}
template <typename Class>
void disconnect(Class& obj) {
m_functions.erase(&obj);
}
template <typename ... Args>
void operator() (Args...args)
{
for (auto& pair : m_functions) {
for (auto& func : pair.second) {
func(args...);
}
}
}
};
I found a way to hash member function which is what i need so i am answering my own question here:
template <typename Class>
size_t getHash(void (Class::*func) (Params...)) {
const char *ptrptr = static_cast<const char*>(static_cast<const void*>(&func));
int size = sizeof (func);
std::string str_rep(ptrptr, size);
std::hash<std::string> strHasher;
return strHasher(str_rep);
}
usage is now simple:
delegate.disconnect(&MyClass::MyFunc);
reference: How to hash and compare a pointer-to-member-function?