I have a comparison/ordering function that relates to a class. I can use it if I define it as a separate closure object. I would like to make it into a static method of the class it operates on so it is tidier. I guessed how to do this but I get an error that I can’t interpret.
Generally I would like to know how to treat static methods as callable objects.
Minimal related example code (not working):
#include <set>
class MyClass {
// More code here
static auto compare(MyClass a, MyClass b) {
return a < b;
}
};
int main() {
std::set<MyClass, decltype(MyClass::compare)> s(MyClass::compare);
return 0;
}
Update, I’m not sure if my example confused the issue, so I updated it.
>Solution :
Couple of issues:
compareis private, make it public.- One must use
&to get the address of functions.
#include <set>
class MyClass {
public:
static auto compare(int a, int b) {
return a < b;
}
};
int main() {
std::set<int, decltype(&MyClass::compare)> s(&MyClass::compare);
return 0;
}