Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use a static method as a callback in c++

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):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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:

  • compare is 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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading