Home > Software design >  How to use a static method as a callback in c
How to use a static method as a callback in c

Time:12-04

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 {
    static auto compare(int a, int b)   {
        return a < b;
    }
};

int main() {
    std::set<int, decltype(MyClass::compare)> s(MyClass::compare);
    return 0;
}

CodePudding user response:

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;
}

CodePudding user response:

Make the function public, and add & in decltype:

std::set<int, decltype(&MyClass::compare)>

I wouldn't consider this to be "tidier" though.

A functor occupies 0 bytes when used as a std::set comparator. But a function pointer (as in your example) occupies 4 or 8 bytes. It also forces you to pass the function to the set's constructor.

Using a function pointer this way only makes sense if you want to switch between different comparators at runtime.

If you do want a pointer, the class itself is unnecessary. You might as well use a free function.

  • Related