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
?
A set is mostly something you will check that data is in it.
So I do not see the point of using one here... You'll have your functions and you'll store them in the set, and after that, what ? You just iterate on them ?
For your question, a element of a set should have a way to generate a hash and an operator==()
. The second is not provided for std::function
and thus you wouldn't be able to check that your function is really in the set.
So even if you find a way to generate an hash from the function, you would be stuck... And I do not see how to meet the hash requirement.
Why not simply use a std::vector
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With