简体   繁体   中英

Pass member function as argument

I have a function that runs a callback:

void run_callback(void(*callback)(uint32_t)) {
    callback(100);
}

This works with static functions,

void global_callback(uint32_t);

int main() {
    run_callback(global_callback);
}

but not with member functions.

class A {
    int x;
  public:
    void callback(uint32_t);
};

int main() {
    A foo;
    run_callback(foo.callback);
}

I work around this with a static wrapper function.

void run_member_callback(void* obj, void(*callback)(void*,uint32_t)) {
    callback(obj, 100);
}

class B {
    int x;
  public:
    static void static_callback(void* obj, uint32_t value) {
        static_cast<B*>(obj)->callback(value);
    }
    void callback(uint32_t);
};

int main() {
    B foo;
    run_member_callback(&foo, foo.static_callback);
}

Is there a simple way to pass a member function as an argument?

edit: I'm trying to avoid STL, and templates aren't an option since my implementation of run_callback is virtual.

You are doing some weird, C-ish things. Use C++ features. I personally would use a template for run_callback and a lambda for passing the member function:

template <class F>
void run_callback(F callback)
{
    callback(100);
}

class A
{
    int x;
  public:
    void callback(uint32_t);
};

int main()
{
    A foo{};
    run_callback([&](uint32_t a) { return foo.callback(a); });
}

If you capture the object by reference take care it outlives the run_callback call. Otherwise capture it by value.


What is a lambda expression in C++11?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM