我希望允许在构建时传递具体的公共成员函数实现。 如果我可以使用其名称调用该公共成员函数,那将是理想的选择。
这个例子可以最好地说明它:
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
}
答案 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
编辑
如果您希望调用者提供实现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)();