c++lambda

C++ lambda operator ==


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.


Solution

  • 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.