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!");
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With