首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将boost::bind与C函数指针混合使用来实现回调

如何将boost::bind与C函数指针混合使用来实现回调
EN

Stack Overflow用户
提问于 2011-07-08 04:52:17
回答 4查看 2K关注 0票数 3

我试图硬塞进一些boost::bind,用成员函数替换直接的C函数指针风格的回调,但我在做显而易见的事情时遇到了问题。谁能告诉我为什么下面的代码片段似乎不能匹配函数调用中的类型?

代码语言:javascript
复制
#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!");
}
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2011-07-08 04:57:12

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

代码语言:javascript
复制
template<typename ToRunT>
void runit(ToRunT const& torun, std::string const& message)
{
    torun(message);
}

或者使用boost::function<>

代码语言:javascript
复制
static void runit(boost::function<void(std::string const&)> const& torun,
                  std::string const& message)
{
    torun(message);
}
票数 4
EN

Stack Overflow用户

发布于 2011-07-08 04:55:12

对于runit的第一个参数,不要使用特定的函数指针签名,而是使用模板。举个例子:

代码语言:javascript
复制
template<typename function_ptr>
void runit(function_ptr torun, const string &message)
{
  torun(message);
}
票数 2
EN

Stack Overflow用户

发布于 2011-07-08 04:57:04

您可以对boost::bind对象使用boost::function类型

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6617031

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档