mercredi 9 septembre 2020

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?

Aucun commentaire:

Enregistrer un commentaire