Reputation: 3820
How do I compare two lambda functions in C++ (Visual Studio 2010)?
std::function<void ()> lambda1 = []() {};
std::function<void ()> lambda2 = []() {};
bool eq1 = (lambda1 == lambda1);
bool eq2 = (lambda1 != lambda2);
I get a compilation error claiming that operator == is inaccessible.
EDIT: I'm trying to compare the function instances. So lambda1 == lambda1 should return true, while lambda1 == lambda2 should return false.
Upvotes: 17
Views: 5621
Reputation: 4215
Simplest answer: All of template<> class function's operator==()s are private.
Followup question: Which if the following did you expect:
- compare address of functions
- compare two distinct objects (of type std::function<void ()>
- compare two abstract functions
Edit (nearly 5 years later):
I find it amusing that there are downvotes without comments. If the downvotes are because C++11 changed the access level for std::function::operator==(), then I say the voter doesn't understand how time works. If the downvotes are because the question asker did not clarify what he imagined operator==() would compare, perhaps the voter should see the multi-hour discussion via comments immediately under the question, which the OP answered only in the comments to my answer.
Upvotes: -3
Reputation: 369498
This is impossible.
Proof sketch: if it were possible to compute
f1 == f2
then it would also be possible to compute
f == infiniteLoop
and solve the Halting Problem.
Upvotes: -1
Reputation: 355107
You can't compare std::function
objects because std::function
is not equality comparable. The closure type of the lambda is also not equality comparable.
However, if your lambda does not capture anything, the lambda itself can be converted to a function pointer, and function pointers are equality comparable (however, to the best of my knowledge it's entirely unspecified whether in this example are_1and2_equal
is true
or false
):
void(*lambda1)() = []() { };
void(*lambda2)() = []() { };
bool are_1and1_equal = (lambda1 == lambda1); // will be true
bool are_1and2_equal = (lambda1 == lambda2); // may be true?
Visual C++ 2010 does not support this conversion. The conversion wasn't added to C++0x until just before Visual C++ was released.
Upvotes: 18
Reputation: 37
You cannot compare functions, end of.
You can at most compare pointers to functions in languages that have that concept (this is also what, for example, EQ does in Lisp. And it fails for equivalent functions that do not occupy the same place in memory.)
Upvotes: 2