开发者

How to mix boost::bind with C function pointers to implement callbacks

开发者 https://www.devze.com 2023-03-17 22:09 出处:网络
I\'m trying to shoehorn in some boost::bind t开发者_如何学Pythono substitute member functions for straight up C function pointer style callbacks, but I\'m running into problems doing the obvious thing

I'm trying to shoehorn in some boost::bind t开发者_如何学Pythono substitute member functions for straight up C function pointer style callbacks, but I'm running into problems doing the obvious thing. Can someone tell me why the following code snippet can't seem to match up the types in the function call?

#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!");
}


The result type of bind is not a function pointer, it's a function object which does not happen to be implicitly convertible to a function pointer. Use a template:

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

Or use boost::function<>:

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


Rather than having a specific function pointer signature for your first argument to runit, use a template. So for instance:

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


You can use boost::function type for boost::bind objects


Pasting the error you get could be useful; however at a guess it's probably due to the fact that "World!" is a string literal (i.e. char[]), not a std::string. Try:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号