加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 如何将boost :: bind与C函数指针混合以实现回调

发布时间:2020-12-16 09:35:52 所属栏目:百科 来源:网络整理
导读:我试图在一些boost :: bind中替换成直接C函数指针样式回调的替换成员函数,但是我遇到了明显问题.有人能告诉我为什么以下代码片段似乎无法匹配函数调用中的类型? #include iostream#include boost/bind.hppusing namespace std;class Foo {public: Foo(const
我试图在一些boost :: bind中替换成直接C函数指针样式回调的替换成员函数,但是我遇到了明显问题.有人能告诉我为什么以下代码片段似乎无法匹配函数调用中的类型?

#include <iostream>
#include <boost/bind.hpp>

using namespace std;

class Foo {
public:
  Foo(const string &prefix) : prefix_(prefix) {}
  void bar(const string &message)
  {
    cout << prefix_ << message << endl;
  }
private:
  const string &prefix_;
};

static void
runit(void (*torun)(const string &message),const string &message)
{
  torun(message);
}

int
main(int argc,const char *argv[])
{
  Foo foo("Hello ");
  runit(boost::bind<void>(&Foo::bar,boost::ref(foo),_1),"World!");
}

解决方法

bind的结果类型不是函数指针,它是一个函数对象,它不会被隐式转换为函数指针.使用模板:

template<typename ToRunT>
void runit(ToRunT const& torun,std::string const& message)
{
    torun(message);
}

或者使用boost::function<>

static void runit(boost::function<void(std::string const&)> const& torun,std::string const& message)
{
    torun(message);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读