std ::将一个成员函数绑定到一个对象指针 [英] std::bind a member function to an object pointer

查看:94
本文介绍了std ::将一个成员函数绑定到一个对象指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有成员函数的类:

pre $ 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 code>在另一个类中,并用它来完成它的工作(而不必为这些函数中的每一个创建类)。我尝试使用类构造函数和 std :: bind 将成员函数的隐式第一个参数绑定到所讨论对象的指针:

  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(父),
m_dirs(dirs),
m_insert(插入)
{}

UPDATE :感谢现在编译的@lijie,但是当调用函数m_insert时,会为 std ::引发一个 std :: exception bad_function_call 。什么可能是错的?谢谢!如果您需要更多信息,请询问!

解决方案

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

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



我认为你要找的是 Target ,你声明
bool insertSourceFile(const std :: string&); 等等,然后你做
std :: bind(& Target :: insertSourceFile, p_target,_1)但这是一种猜测,直到意图得到澄清为止。


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!

解决方案

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.

这篇关于std ::将一个成员函数绑定到一个对象指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆