简体   繁体   中英

Passing public member function pointer to a constructor

I want to allow for passing a concrete public member function implementation at construction time. It would be ideal if I could call that public member function using its name.

This example can illustrate it the best:

class A {
    typedef int (A::*mem)(void) const;

public:
    A(int aa) : a(aa) {};
    A(int aa, mem mm) : m(mm), a(aa) {}; // How to use this?

    mem m;

private:
    int a;
};

int main() {
    A a(3);
    // (a.*m)(); // ‘m’ was not declared in this scope
}

Suppose A has a member function named foo (matching the signature of typedef mem ), then you can

A a(3, &A::foo); // pass member function pointer pointing to A::foo
(a.*(a.m))();    // call from the member function pointer on object a

LIVE

EDIT

If you want the caller to provide the implementation liek lambda, you can use std::function instead.

class A {
    typedef std::function<int()> mem;

public:
    A(int aa) : a(aa) {};
    A(int aa, mem mm) : m(mm), a(aa) {}; // How to use this?

    mem m;

private:
    int a;
};

then

A a(3, [] { std::cout << "hello"; return 0; });
(a.m)(); 

LIVE

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