Reputation: 93
can someone explain me why this code won't build:
std::function<void(int)> intcb = [](int a)
{
std::cout << "callback: " << a << std::endl;
};
std::list<std::function<void(int)>> list;
list.push_back(intcb);
list.remove(intcb);
build error located in remove function:
no match for 'operator==' (operand types are 'std::function<void(int)>' and 'const value_type' {aka 'const std::function<void(int)>'})
thanks for your help
Upvotes: 3
Views: 441
Reputation: 174
Does this make sense: what you have in your list is function object and while you put it to the list you're actually copying the intcb. So you need a way to compare the copies. Instead you can try storing by pointer, so removing will work by comparing addresses which works out of the box.
#include <iostream>
#include <list>
#include <functional>
std::function<void(int)> intcb = [](int a)
{
std::cout << "callback: " << a << std::endl;
};
int main() {
std::list<std::function<void(int)>*> list;
list.push_back(&intcb);
list.remove(&intcb);
return 0;
}
Upvotes: 0
Reputation: 51
Well, you want to create a list of functions and then enable "remove" functionality, but for removal operation list needs to be able to compare instances of its type, because it does not rely on references to objects.
So you need to somehow define operator==
for your specified function type
Upvotes: 5