2010-11-23 120 views
3

我有成員函數類:的std ::一個成員函數綁定到對象指針

typedef std::function<bool (const std::string &)> InsertFunction;  

bool insertSourceFile(const std::string &); 
bool insertSourceDir(const std::string &); 
bool insertHeaderFile(const std::string &); 
bool insertHeaderDir(const std::string &); 

我想有這些InsertFunction S IN另一個類中的一個的參考,並用它來做好自己的工作(不必爲這些功能中的每一個做類)。我嘗試使用類構造函數和std::bind的成員函數的隱式第一個參數綁定到對象的問題指針:

new ListParser(p_target->sourceDirs(), bind(&Target::insertSourceFile, p_target, _1), this); 

ListParser::ListParser(const stringSet &dirs, const InsertFunction &insert, 
         State* parent = 0) 
: ParserState(parent), 
    m_dirs(dirs), 
    m_insert(insert) 
{ } 

UPDATE:感謝@lijie時,現在編譯源程序,但是當函數m_insert被調用時,std::bad_function_call被拋出std::exception。什麼可能是錯的?謝謝!如果您需要更多信息,請詢問!

回答

2

在您的代碼中,insertSourceFile方法,返回std::function<etc>。在你的綁定調用中,你正在執行調用該方法的Target::insertSourceFile()。因此,錯誤。

編輯 具體來說,Target :: insertSourceFile不是一個接受字符串並返回布爾值的函數。

我想你在找什麼是Target,你聲明 bool insertSourceFile(const std::string &);等,然後你做 std::bind(&Target::insertSourceFile, p_target, _1)但是這是一個猜測,直到意圖澄清。

+0

謝謝,我用更正的語法更新了這個問題。我確實希望使用m_insert作爲一個函數,它使用`const std :: string&`並返回一個`bool`,並且該函數是`p_target`(因此是綁定)中的一個。 – rubenvb 2010-11-23 15:58:26