簡體   English   中英

是否可以在數組中保存具有不同參數的成員函數?

[英]Is it possible to hold member functions with different arguments in an array?

假設我有

void a::f1()
void a::f2(int)
void a::f3(const std::string&)

我可以使用數組來存儲類似

ary1 = {&a::f1, bind(&a::f2, 2), bind(&a::f3, "abc"}
ary2 = {&a::f1, bind(&a::f3, "def")}

只要可調用對象具有相同的簽名,就可以在std::function存儲不同的可調用對象,例如:

struct A {
    void f1();
    void f2(int);
    void f3(const std::string&);
};

int main() {
    std::function<void(A&)> functions[] = {
          &A::f1
        , [](A& a) { a.f2(2); }
        , [](A& a) { a.f3("abc"); }
        , std::bind(&A::f3, std::placeholders::_1, "abc") 
    };

    A a;
    for(auto& f : functions)
        f(a);
}

請注意,我在這里使用了lambda表達式而不是std::bind因為lambda是最佳實踐:更容易編寫,閱讀和更有效。

暫無
暫無

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

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