3

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!

rubenvb
  • 74,642
  • 33
  • 187
  • 332

1 Answers1

2

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.

lijie
  • 4,811
  • 22
  • 26
  • Thanks, I have updated the question with corrected syntax. I indeed want to use m_insert as a function taking a `const std::string &` and returning a `bool`, and that function being the one in `p_target` (hence the bind). – rubenvb Nov 23 '10 at 15:58
  • Never mind, I stored a const reference to the function object created as temporary by `bind`, which resulted in an empty function object in some weird way. It now works and calls the right function! Thanks again! – rubenvb Nov 23 '10 at 16:23