代码之家  ›  专栏  ›  技术社区  ›  rubenvb

std::将成员函数绑定到对象指针

  •  3
  • rubenvb  · 技术社区  · 14 年前

    我有一个成员函数类:

    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 在另一个类中,并使用它来完成其工作(不必为这些函数中的每一个函数创建类)。我试着使用类构造函数 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 )
    {    }
    

    更新 :多亏了@lijie,源代码现在可以编译了,但是当调用m_insert函数时 std::exception 是为了 std::bad_function_call . 怎么了?谢谢!如果你需要更多的信息,请询问!

    1 回复  |  直到 14 年前
        1
  •  2
  •   lijie    14 年前

    在你的代码中, insertSourceFile 是一个 方法 返回一个 std::function<etc> . 在你被绑的电话里,你在做 Target::insertSourceFile() 它正在调用方法。因此,错误。

    编辑 具体来说,Target::insertSourceFile不是接受字符串并返回布尔值的函数。

    我想你要找的是 Target ,您声明 bool insertSourceFile(const std::string &); ,等等,然后 std::bind(&Target::insertSourceFile, p_target, _1) 但这只是一个猜测,直到意图被澄清。