比较std :: functions与存储在其中的lambda的相等性

问题描述

我正在使用以下功能测试use Illuminate\Contracts\Auth\MustVerifyEmail; ... class User extends Model implements MustVerifyEmail 的相等性。该功能的灵感来自SO discussion here

std::function

现在,如果我通过以下测试来验证其是否正常工作

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);
}

为什么#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? } 在通过lambda时崩溃?我对lambda做错了,还是AreEqual缺乏比较AreEqual s中存储的lambda的逻辑?

解决方法

您可以使用以下功能进行精确操作。

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));
}

Lambda不是std::function<>

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...