如何混合boost::bind与C函数指针来实现回调
How to mix boost::bind with C function pointers to implement callbacks
我试图硬塞进一些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!");
}
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);
}
不要为runit
的第一个参数使用特定的函数指针签名,而是使用模板。例如:
template<typename function_ptr>
void runit(function_ptr torun, const string &message)
{
torun(message);
}
对于boost::bind对象,可以使用boost::function类型
粘贴你得到的错误可能是有用的;然而,在猜测这可能是由于"World!"
是一个字符串字面值(即char[]
),而不是std::string
。试一试:
runit(boost::bind<void>(&Foo::bar, boost::ref(foo)), std::string("World!"));
相关文章:
- QMetaObject invokeMethod的基于函数指针的语法
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- c++r值引用应用于函数指针
- 模板函数指针和lambda
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 带有类的函数指针
- () 函子后面的括号,而不是函数指针?
- 全局作用域中函数指针的赋值
- 使用"Task"函数指针队列定义作业管理器
- 将成员函数指针作为参数传递给模板方法
- 如何创建对象函数指针C++映射?
- 匹配函数指针作为模板参数?
- 通过函数指针定义类范围之外的方法
- 存储在类中的函数指针
- C++从函数指针数组调用函数
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 整数键映射到头文件中的成员函数指针
- 从类成员函数到类 C 函数指针的转换
- 如何将内联匿名函数分配给C++函数指针
- 将字符缓冲区强制转换为函数指针