TheWaterProgrammer
TheWaterProgrammer

Reputation: 8229

Comparing equality of std::functions with lambdas stored in them

I am using the following function to test equality of std::functions. The function is inspired from the SO discussion here

template<typename T, typename... U>
inline bool AreEqual(std::function<T(U...)> function_1, std::function<T(U...)> function_2) {

    typedef T(fnType)(U...);
    fnType ** f_ptr_1 = function_1.template target<fnType*>();
    size_t f1 = (size_t) *f_ptr_1;
    fnType ** f_ptr_2 = function_2.template target<fnType*>();
    size_t f2 = (size_t) *f_ptr_2;

    return (f1 == f2);
}

Now if I have the below test to verify that its working

#include "gtest/gtest.h"

void DummyFunc(bool value) {
    value = true;
}

TEST(Some_Test, verify_equality_of_std_functions) {
    typedef std::function<void(bool)> FuncType1;

    FuncType1 f2 = &DummyFunc;
    EXPECT_TRUE(AreEqual(f2, f2));  // This passes as expected

    auto test_lambda = [](bool dummy_param) {
        dummy_param = true;
    };

    FuncType1 f1 = test_lambda;
    EXPECT_TRUE(AreEqual(f1, f1));  // But, this causes a crash! Why?
}

Why does AreEqual crash when passing a lambda? Am i doing something wrong with the lambda or is it that AreEqual lacks logic to compare lambdas stored in std::functions?

Upvotes: 0

Views: 521

Answers (1)

D-RAJ
D-RAJ

Reputation: 3372

You can use the following function to do the exact.

template<class RET, class... Args>
inline bool AreEqual(RET(*f1)(Args&...), RET(*f2)(Args&...))
{
    return f1 == f2;
}

TEST(Some_Test, verify_equality_of_std_functions) {
    typedef std::function<void(bool)> FuncType1;

    FuncType1 f2 = DummyFunc;
    EXPECT_TRUE(AreEqual(*f2.target<void(*)()>(), *f2.target<void(*)()>())); 

    auto test_lambda = [](bool dummy_param) {
        dummy_param = true;
    };
    
    /* Lambdas are required to be converted to raw function pointers. */
    void(*f1)() = test_lambda;
    EXPECT_TRUE(AreEqual(f1, f1));
}

Lambdas are not std::function<>s.

Upvotes: 2

Related Questions