【问题标题】:std::bind a member function to an object pointerstd::将成员函数绑定到对象指针
【发布时间】:2010-11-23 15:29:35
【问题描述】:

我有成员函数的类:

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

我想在另一个类中引用其中一个InsertFunctions,并用它来完成它的工作(不必为每个函数创建类)。我尝试使用类构造函数和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::bad_function_call 会抛出一个std::exception。有什么问题?谢谢!如果您需要更多信息,请询问!

【问题讨论】:

    标签: c++11 functional-programming


    【解决方案1】:

    在您的代码中,insertSourceFile 是一个返回std::function&lt;etc&gt;方法。在您的绑定调用中,您正在执行Target::insertSourceFile(),它正在调用该方法。因此,错误。

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

    我认为您正在寻找的是Target,您声明 bool insertSourceFile(const std::string &amp;); 等然后你做 std::bind(&amp;Target::insertSourceFile, p_target, _1) 但在意图明确之前,这只是猜测。

    【讨论】:

    • 谢谢,我已经用更正的语法更新了这个问题。我确实想使用 m_insert 作为一个函数,它接受一个const std::string &amp; 并返回一个bool,并且该函数是p_target 中的一个(因此绑定)。
    • 没关系,我存储了对由bind 创建的临时函数对象的 const 引用,这以某种奇怪的方式导致了一个空的函数对象。它现在可以工作并调用正确的函数!再次感谢!
    猜你喜欢
    • 1970-01-01
    • 2010-12-27
    • 1970-01-01
    • 2012-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多