I know how to pass a regular comparison class or function to set::set<>.
I am writing some test code and I want to emulate some C libraries using STL's std::set and I want to be able to pass a C callback to the comparison object so a different comparison takes place.
I have the following theoretical code:
struct MyClass
{
int a;
};
typedef bool (*user_callback_t)(void *, void *);
class MyComparison
{
private:
user_callback_t cb = nullptr;
public:
MyComparison(user_callback_t cb): cb(cb) { }
MyComparison() {}
bool operator()(const MyClass &a, const MyClass &b) const
{
return cb((void *)&a, (void *)&b);
}
};
int f1()
{
auto cmp = [](void *a, void *b) -> bool
{
return *(int *)a < *(int *)b;
};
MyComparison mycmp(cmp);
std::set<MyClass, MyComparison> m1;
m1.insert({ 1 });
m1.insert({ 2 });
m1.insert({ 3 });
return 0;
};
Now notice how I can do:
std::set<MyClass, MyComparison> m1;
But I cannot, somehow, instantiate a MyComparison object, pass it "cmp" and then use that initialize comparison object with that specific set.
Is there a way to achieve that?