开发者

std::bind a member function to an object pointer

I have class with member functions:

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 & );

I'd like to have a reference to one of these InsertFunctions in another class, and use it to do its job (without having to make classes for each of these functions). I tried using the class constructor and std::bind to bind the member function's implicit first argument to a pointer of the object in question:

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

with

ListParser::ListParser( const stringSet &dirs, const InsertFunction &insert,
                        State* parent = 0 )
:   ParserState( pare开发者_运维百科nt ),
    m_dirs( dirs ),
    m_insert( insert )
{    }

UPDATE: thanks to @lijie, the source now compiles, but when the function m_insert is called, a std::exceptionis thrown for std::bad_function_call. What could be wrong? Thanks! If you need more info, please ask!


In your code, insertSourceFile is a method that returns a std::function<etc>. In your bind call, you are doing Target::insertSourceFile() which is invoking the method. Hence, the error.

EDIT Specifically, Target::insertSourceFile is not a function that takes a string and returns a boolean.

I think what you are looking for is in Target, you declare bool insertSourceFile(const std::string &);, etc. and then you do std::bind(&Target::insertSourceFile, p_target, _1) but that is a guess until the intention is clarified.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜