I have a vector of std::function
objects defined like this:
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. My first attempt was using the std::find
function, like this:
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). So I tried using std::find_if
to make use of the std::function::target()
method:
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. Intrigued, I tried writing a find
function by hand to see what is happening, but I had no success, got the same error:
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?
As shown here, template member function target
accepts type that is compared with a stored object type. In you case it is a pointer to a 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). I think you should consider using plain pointers instead of std::function
here.