A set
has the requirement that its elements may be ordered using <
. So to put functions in a set, you have to define an ordering for functions first. For example, this comparison considers all functions with the same type as equal:
#include <set>
#include <functional>
using namespace std;
typedef function<void(int)> fun;
bool operator<(const fun& f1, const fun& f2) {
return f2.target_type().name() < f2.target_type().name();
}
int main() {
set<fun> fset;
}
Likewise, for an unordered_set
, you'd have to define a specialization of std::hash<fun>
.
Edit: I've borrowed the target
idea from another solution to make the comparison well-defined.
Edit2: The most meaningful comparison for arbitrary functions would probably look like this:
struct fun_comp {
template<typename Fun1, typename Fun2>
bool operator()(const Fun1& f1, const Fun2& f2) {
const char* c1 = f1._M_functor._M_pod_data;
const char* c2 = f2._M_functor._M_pod_data;
size_t sz = sizeof(f1._M_functor._M_pod_data);
return lexicographical_compare(c1, c1+sz, c2, c2+sz);
}
};
This is, obviously, completely unportable, depends on libstdc++
-internals and will only compile with -fno-access-control
, so you probably shouldn't actually do it like this.