Why can't I use std::function as a std::set or std::unordered_set value type?

  • A+

Why can't I have a std::set or std::unordered_set of std::functions?

Is there any way to get it to work anyway?


You can very well create an std::set of functions. The problem is that sets require an absolute order to exist between the values of its elements. This order is defined by a comparator that is then used to sort the elements of a set, to check if an element already exists, and to find a specific element back.

Unfortunately, there doesn't exist an order between functions. Suppose, that you have two functions f1() and f2(), what would be the meaning of f1 < f2 ?

Also equality is not really defined. For example, if you have

int fun1(int) { return 1; } int fun2(int) { return 1; } function<int(int)> f1=fun1, f2=fun2;  

Should f1 and f2 be the same value if you'd insert them in a set (because it's always the same result), or is it something different (because it's different functions even though they have the same body) ?

Of course, you could trick the compiler in letting it believe that you have defined an order:

struct Comp {     using T = function<int(int)>;     bool operator()(const T &lhs, const T &rhs) const      {         return &lhs < &rhs;     } };  set <function<int(int)>,Comp> s;  

You could then insert functions in the set. But this will not work very well, because you take the address of the element, and if the same elements are swapped, the order is different.

I think that the best way to proceed, would be to use a wrapper with a member string that defines an id and use this id to sort the elements in the set (or to do the hashing in case of an unordered_set)


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: