将公共成员函数指针传递给构造函数

时间:2020-04-27 02:11:04

标签: c++

我希望允许在构建时传递具体的公共成员函数实现。 如果我可以使用其名称调用该公共成员函数,那将是理想的选择。

这个例子可以最好地说明它:

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
}

1 个答案:

答案 0 :(得分:4)

假设A有一个名为foo的成员函数(与typedef mem的签名匹配),那么您可以

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

编辑

如果您希望调用者提供实现liek lambda,则可以改用std::function

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

然后

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

LIVE

相关问题