Reputation: 76
I am trying to create a set of function pointers in c++ but getting error while inserting / deleting elements from it.
#include<bits/stdc++.h>
using namespace std;
void func(int x) {
cout<<x;
}
int main() {
set <function<void (int)>> mine;
mine.insert(func);
return 0;
}
i am getting error /usr/include/c++/6/bits/stl_function.h:386:20: error: no match for ‘operator<’ (operand types are ‘const std::function’ and ‘const std::function’). I think that this problem is because of operator that will be used to compare set values , can someone suggest how to make this work ? How can i write a comparator for function pointers in this case ?
Upvotes: 0
Views: 1247
Reputation: 23701
If you want to store just function pointers, you don't need std::function
:
using MyFunctionPointer = void(*)(int);
void func(int x);
std::set<MyFunctionPointer> orderedSet;
int main()
{
orderedSet.emplace(func);
}
This works because you can compare (for std::set
) or hash (for std::unordered set
) function pointer values. But comparing or hashing std::function
instances is not implemented in the standard library, and there is no portable way to add that after the fact.
Edit: As pointed out by @HolyBlackCat, while the builtin operator<
is not required to induce the required total order on function pointers, std::less
(as used by std::set
) is required to do so for any pointer.
Upvotes: 3