I need to create a templated class that can hold pointers to elements of type T
and then performs functions on them. The functions will come from different places, so I need a container to store them, so I can call them later. I decided to use an std::unordered_set
, because it offers speed and restricts duplication due to it being implemented as a hash table. I have a whole class written, but it doesn't compile due to there not being a hash function defined for my std::function
that takes a pointer of type T
and returns void
. It's easy enough to specify it with struct hash<std::function<void(MyCustomType*)>>
(and overloading the ()
operator, too) for each type I use, but how do I actually hash the function?
Here is a watered-down excerpt from my class with the relevant members and methods:
template <typename T>
class Master {
private:
std::unordered_set<std::function<void(T*)>> functions;
protected:
registerFunction(std::function<void(T*)> function) {
this->functions.insert(function);
}
unregisterFunction(std::function<void(T*)> function) {
this->functions.erase(function);
}
};
I'm not completely bound to using an std::unordered_set
, but it seems to offer everything that I'd need to get this piece (and the rest of my code) working well.
Am I thinking about this the wrong way? Is it completely impossible to hash a std::function
?
std::function
could hold any functor of any compatible type. That's the whole point of it, type erasure. Without access to that thing it contains, you can't hash it (or compare values). And even ifstd::function
wanted to give you access it basically can't: you can't write a function that does anything with it because the type could be anything. – Marrin