C++ 如何混合boost::bind和C函数指针来实现回调

C++ 如何混合boost::bind和C函数指针来实现回调,c++,boost,C++,Boost,我试图插入一些boost::bind来替换直接向上的C函数指针式回调的成员函数,但在做显而易见的事情时遇到了问题。有人能告诉我为什么下面的代码片段似乎与函数调用中的类型不匹配吗 #include <iostream> #include <boost/bind.hpp> using namespace std; class Foo { public: Foo(const string &prefix) : prefix_(prefix) {} void

我试图插入一些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!");
}
#包括
#包括
使用名称空间std;
福班{
公众:
Foo(常量字符串和前缀):前缀{(前缀){}
空栏(常量字符串和消息)
{

不能使用模板,而不是为运行它的第一个参数指定特定的函数指针签名。例如:

template<typename function_ptr>
void runit(function_ptr torun, const string &message)
{
  torun(message);
}
模板
void runit(函数、常量字符串和消息)
{
托伦(信息);
}

您可以对boost::bind对象使用boost::function type

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

template<typename ToRunT>
void runit(ToRunT const& torun, std::string const& message)
{
    torun(message);
}
模板
void runit(ToRunT const&torun,std::string const&message)
{
托伦(信息);
}
或使用:

static void runit(boost::function const&torun,
std::字符串常量和消息)
{
托伦(信息);
}

粘贴您得到的错误可能会很有用;但是猜测可能是因为
“World!”
是字符串文字(即
char[]
),而不是
std::string
。请尝试:

runit(boost::bind<void>(&Foo::bar, boost::ref(foo)), std::string("World!"));
runit(boost::bind(&Foo::bar,boost::ref(Foo)),std::string(“World!”);

为什么要这样做?你想获得什么好处?@AJG85-我有一个C库,可供多个C程序使用(这使我无法修改头/实现)我想开发一个新的C++程序,使用一些所提供的功能。特别是有一些地方我想调用一个可能的库函数集合(具有相同的签名,保存函数名)。通过一种通用的回调机制。如果必须的话,
boost::function
的typedef和将
const&
带到名称空间中的typedef的函数应该可以工作。然后,您可以在调用名称空间函数时使用
boost::bind
。它的实际术语是
bind\u expression
>(请参阅相关的mpl谓词)对这两种方法都进行了测试,它们工作得很好。谢谢!隐式转换将通过
std::string
runit(boost::bind<void>(&Foo::bar, boost::ref(foo)), std::string("World!"));