2010-05-25 88 views
3
#include <boost/bind.hpp> 
#include <iostream> 

using namespace std; 
using boost::bind; 

class A { 
public: 
    void print(string &s) { 
     cout << s.c_str() << endl; 
    } 
}; 


typedef void (*callback)(); 

class B { 
public: 
    void set_callback(callback cb) { 
     m_cb = cb; 
    } 

    void do_callback() { 
     m_cb(); 
    } 

private: 
    callback m_cb; 
}; 

void main() { 
    A a; 
    B b; 
    string s("message"); 
    b.set_callback(bind(A::print, &a, s)); 
    b.do_callback(); 

} 

所以我想要做的是當b的回調被激活時,讓流「message」的打印方法給cout。我收到來自msvc10的意外數量的參數錯誤。我確定這是超級新手基本,我很抱歉提前。Noob boost :: bind成員函數回調問題

回答

9

typedef boost::function<void()> callback;

一個綁定的功能替代typedef void (*callback)();不會產生普通的功能,所以你不能僅僅將其存儲在一個普通函數指針。然而,boost::function能夠處理任何東西,只要它可以用正確的簽名調用,所以這就是你想要的。它將與函數指針或通過綁定創建的仿函數一起工作。

一些修正你的代碼後,我想出了這個:

#include <boost/bind.hpp> 
#include <boost/function.hpp> 
#include <iostream> 

// i prefer explicit namespaces, but that's a matter of preference 

class A { 
public: 
    // prefer const refs to regular refs unless you need to modify the argument! 
    void print(const std::string &s) { 
     // no need for .c_str() here, cout knows how to output a std::string just fine :-) 
     std::cout << s << std::endl; 
    } 
}; 


// holds any arity 0 callable "thing" which returns void 
typedef boost::function<void()> callback; 

class B { 
public: 
    void set_callback(callback cb) { 
     m_cb = cb; 
    } 

    void do_callback() { 
     m_cb(); 
    } 

private: 
    callback m_cb; 
}; 

void regular_function() { 
    std::cout << "regular!" << std::endl; 
} 

// the return type for main is int, never anything else 
// however, in c++, you may omit the "return 0;" from main (and only main) 
// which will have the same effect as if you had a "return 0;" as the last line 
// of main 
int main() { 
    A a; 
    B b; 
    std::string s("message"); 

    // you forget the "&" here before A::print! 
    b.set_callback(boost::bind(&A::print, &a, s)); 
    b.do_callback(); 

    // this will work for regular function pointers too, yay! 
    b.set_callback(regular_function); 
    b.do_callback(); 

} 
+0

感謝您的幫助。 – shaz 2010-05-25 19:29:53

相關問題