2016-03-16 53 views
1

將一個類的成員函數傳遞給另一個類的std::function的正確方法是什麼?將對象的函數傳遞給另一個類的另一個std ::函數

例如,下面的Bar想存儲一個Foo對象的函數。

class Foo { 
public: 
    Foo(int x) : data(x) {} 
    bool isEven(int y) { return (data + y) & 0x01; } 
    int data; 
}; 

class Bar { 
public: 
    std::function<bool(int)> testFunction; 
}; 


int main() { 
    Foo foo1(1); 
    Bar bar; 
    bar.testFunction = std::bind(&Foo::isEven, &foo1); 
    if (bar.testFunction(3)) { 
    std::cout << "is even" << std::endl; 
    } 
    return 0; 
} 

這並不編譯:

no match for 'operator=' (operand types are 'std::function<bool(int)>' and 'std::_Bind_helper<false, bool (Foo::*)(int), Foo*>::type {aka std::_Bind<std::_Mem_fn<bool (Foo::*)(int)>(Foo*)>}')** 

回答

1

您可以使用lambda:

bar.testFunction = [&foo1](int x){ return foo1.isEven(x); }; 
3

Foo::isEven需要它,你會在後面傳遞一個參數,所以你需要添加一個佔位符來表明這個未綁定的參數。

bar.testFunction = std::bind(&Foo::isEven, &foo1, std::placeholders::_1); 

或者只是使用lambda代替bind

bar.testFunction = [&foo1](int x) { return foo1.isEven(x); }; 
相關問題