I believe this is not a duplicate question. Other similar questions ask something like “how can I compare std::function objects for equivalence/equality?”. The answer seems to be simply “one cannot”. Instead, I am asking “how can I represent a function that includes captures and can be compared for equality?”.
Taking a step back: I am defining a callback type, and “clients” will “register” with the callback “notifier”. The notifier must be able to prevent duplicate callbacks from being registered, and allow for removal of specified callbacks. I started simply with:
typedef bool(*Callback)(const MyClass&);
As the design progressed, I realized I would need to support (also, but not only) member functions as callbacks, which I represented as lambdas:
auto myLambda = [this](const MyClass& myclass) {...};
Researching how to declare this type, I ran across several sites suggesting use of std::function. My typedef then became:
typedef std::function<bool(const myClass&)> Callback;
So I construct a std::vector to hold my Callbacks. Finding a Callback became a problem. I thought I had solved the problem with:
bool findCallback(const Callback& cb, const std::vector<Callback>& callback_v) {
std::find_if(callback_v.begin(), callback_v.end(),[cb](Callback& other) {
return *cb.target<bool(const MyClass&)>()==*other.target<bool(const MyClass&)>();
}) != callback_v.end();
}
This does not work, as any comparison always results in a match. So the question is not “how to compare std::function<> objects”, but rather “how can I represent callbacks including both static and member functions in such a way as to have a consistent signature as an element in a container (std::vector) and supporting comparison for equality?”.
13