我有一个std::function
对象的向量,定义如下:
std::vector<std::function<void()>> funcs = { myFunc1, myFunc2, myFunc3 };
//The functions are defined like this:
//void myFunc1() { ... }
我正在尝试通过此数组搜索特定功能。我的第一次尝试是使用std::find
函数,如下所示:
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==()
不会比较相等的困难方式。因此,我尝试使用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
函数以查看发生了什么,但是我没有成功,但遇到了相同的错误:
auto iter = funcs.begin();
for (; iter != funcs.end(); iter++)
if (*iter->target<void()>() == myFunc2)
break;
所以这是问题。如何比较2个std::function
对象以查看它们是否存储相同的功能?
如图here所示,模板成员函数target
接受与存储对象类型进行比较的类型。在您的情况下,它是对函数的指针。您必须更改
*iter->target<void()>() == myFunc2
to
*iter->target<void(*)()>() == myFunc2
请注意,这只会让您找到平面C函数,而不是任意可调用对象(例如lambda函数)。我认为您应该考虑使用普通指针而不是std::function
。