Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing std::functions for equality?

How can I compare two C++11 std::functions with operator==, and return true if both of said functions refer to the same function pointer?

like image 420
JesseTG Avatar asked Dec 30 '13 04:12

JesseTG


People also ask

How do you compare functions in C++?

The compare() function in C++ C++ has in-built compare() function in order to compare two strings efficiently. The compare() function compares two strings and returns the following values according to the matching cases: Returns 0, if both the strings are the same.

How do you compare function pointers?

Two function pointers can be compared with the == and != operators, just like any other kind of pointers. We can also compare a function pointer to the NULL pointer using the == and != operators.

What is std :: less?

The std::less is a is a member of the functional class (<functional. h>) used for performing comparisons.


Video Answer


2 Answers

operator== for std::function compares a std::function with a null pointer, as far as I can tell the standard does not provide any details as to why.

Although, this boost FAQ entry, Why can't I compare boost::function objects with operator== or operator!=? provides a rationale and as far as I can tell should be applicable to std::function as well. Quoting the FAQ:

Comparison between boost::function objects cannot be implemented "well", and therefore will not be implemented. [...]

it then outlines requested solutions similar to Preet's and goes on to say:

The problem occurs when the type of the function objects stored by both f and g doesn't have an operator==[...]

and explains why this has to has to be dealt with in either the assignment operator or constructor and then goes on to say:

All of these problems translate into failures in the boost::function constructors or assignment operator, even if the user never invokes operator==. We can't do that to users.

Update

Found a standards rationale in Accessing the target of a tr1::function object, which is pretty old but is consistent with the boost FAQ and says:

operator== is unimplementable for tr1::function within the C++ language, because we do not have a reliable way to detect if a given type T is Equality Comparable without user assistance.

like image 57
Shafik Yaghmour Avatar answered Sep 20 '22 16:09

Shafik Yaghmour


You can actually get it to work with .target:

template<typename T, typename... U> size_t getAddress(std::function<T(U...)> f) {     typedef T(fnType)(U...);     fnType ** fnPointer = f.template target<fnType*>();     return (size_t) *fnPointer; }  if (getAddress(f) == getAddress(g)) {...} 

(Ref: C++ trying to get function address from a std::function)

like image 33
P i Avatar answered Sep 18 '22 16:09

P i