Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
586 views
in Technique[技术] by (71.8m points)

c++11 - 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( parent ),
    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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...