[英]How can I compare std::function objects?
I have a vector of std::function
objects defined like this:我有一个std::function
对象的向量,定义如下:
std::vector<std::function<void()>> funcs = { myFunc1, myFunc2, myFunc3 };
//The functions are defined like this:
//void myFunc1() { ... }
I am trying to search through this array for a specific function.我正在尝试在此数组中搜索特定的 function。 My first attempt was using the std::find
function, like this:我的第一次尝试是使用std::find
function,如下所示:
auto iter = std::find(funcs.begin(), funcs.end(), myFunc2);
//CS2679: binary '==': no operator found which takes a right-hand operator of type '_Ty (__cdecl &)' or there is no acceptable conversion
I learned the hard way that std::function::operator==()
does not compare equal unless the function objects are empty (clearly not the case).我学到了std::function::operator==()
不比较相等的艰难方法,除非 function 对象为空(显然不是这种情况)。 So I tried using std::find_if
to make use of the std::function::target()
method:所以我尝试使用std::find_if
来使用std::function::target()
方法:
auto iter = std::find_if(funcs.begin(), funcs.end(), [](const std::function<void()>& f)
{
if (*f.target<void()>() == myFunc2)
//using or not using that '*' before f in the condition makes no difference in the error
return true;
return false;
});
My compiler (VC++ 2019) still complained with the same exact error.我的编译器(VC++ 2019)仍然抱怨同样的错误。 Intrigued, I tried writing a find
function by hand to see what is happening, but I had no success, got the same error:很好奇,我试着手动写了一个find
function 看看发生了什么,但我没有成功,得到了同样的错误:
auto iter = funcs.begin();
for (; iter != funcs.end(); iter++)
if (*iter->target<void()>() == myFunc2)
break;
So here is the question.所以这就是问题所在。 How can I compare 2 std::function
objects to see if they store the same function?如何比较 2 个std::function
对象以查看它们是否存储相同的 function?
As shown here , template member function target
accepts type that is compared with a stored object type.如此处所示,模板成员 function target
接受与存储的 object 类型进行比较的类型。 In you case it is a pointer to a function.在您的情况下,它是指向 function 的指针。 You have to change你必须改变
*iter->target<void()>() == myFunc2
to至
*iter->target<void(*)()>() == myFunc2
Note that this will only only you to find a plain C function, not an arbitrary callable object (like a lambda function). Note that this will only only you to find a plain C function, not an arbitrary callable object (like a lambda function). I think you should consider using plain pointers instead of std::function
here.我认为您应该考虑在这里使用普通指针而不是std::function
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.