Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

boost

I'm trying to shoehorn in some boost::bind to 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!");
}
like image 358
BD at Rivenhill Avatar asked Aug 01 '26 01:08

BD at Rivenhill


2 Answers

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);
}
like image 78
ildjarn Avatar answered Aug 02 '26 15:08

ildjarn


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);
}
like image 45
Jason Avatar answered Aug 02 '26 13:08

Jason



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!