簡體   English   中英

將公共成員 function 指針傳遞給構造函數

[英]Passing public member function pointer to a constructor

我想允許在施工時通過具體的公共成員 function 實現。 如果我可以使用它的名稱調用該公共成員 function,那將是理想的。

這個例子可以最好地說明它:

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
}

假設A有一個名為foo的成員 function (匹配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

居住

編輯

如果您希望調用方提供實施方式 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)(); 

居住

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM