问题描述
我正在使用以下功能测试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<>
。