[英]How can I compare comparing contents of std::vectors with custom objects
[英]How can I compare std::function objects?
我有一个std::function
对象的向量,定义如下:
std::vector<std::function<void()>> funcs = { myFunc1, myFunc2, myFunc3 };
//The functions are defined like this:
//void myFunc1() { ... }
我正在尝试在此数组中搜索特定的 function。 我的第一次尝试是使用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
我学到了std::function::operator==()
不比较相等的艰难方法,除非 function 对象为空(显然不是这种情况)。 所以我尝试使用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;
});
我的编译器(VC++ 2019)仍然抱怨同样的错误。 很好奇,我试着手动写了一个find
function 看看发生了什么,但我没有成功,得到了同样的错误:
auto iter = funcs.begin();
for (; iter != funcs.end(); iter++)
if (*iter->target<void()>() == myFunc2)
break;
所以这就是问题所在。 如何比较 2 个std::function
对象以查看它们是否存储相同的 function?
如此处所示,模板成员 function target
接受与存储的 object 类型进行比较的类型。 在您的情况下,它是指向 function 的指针。 你必须改变
*iter->target<void()>() == myFunc2
至
*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). 我认为您应该考虑在这里使用普通指针而不是std::function
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.