我试图硬塞进一些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!");
}发布于 2011-07-08 04:57:12
bind的结果类型不是函数指针,它是一个碰巧不能隐式转换为函数指针的函数对象。使用模板:
template<typename ToRunT>
void runit(ToRunT const& torun, std::string const& message)
{
torun(message);
}或者使用boost::function<>
static void runit(boost::function<void(std::string const&)> const& torun,
std::string const& message)
{
torun(message);
}发布于 2011-07-08 04:55:12
对于runit的第一个参数,不要使用特定的函数指针签名,而是使用模板。举个例子:
template<typename function_ptr>
void runit(function_ptr torun, const string &message)
{
torun(message);
}发布于 2011-07-08 04:57:04
您可以对boost::bind对象使用boost::function类型
https://stackoverflow.com/questions/6617031
复制相似问题