如何使用 boost::bind 将静态成员函数绑定到 boost::function
How to bind a static member function to a boost::function using boost::bind
我想使用 boost::
bind 将静态成员函数绑定到 boost::function。以下是我想做什么(不工作)的示例。
class Foo {
public:
static void DoStuff(int param)
{
// To do when calling back
}
};
class Question {
public:
void Setup()
{
AssignCallback(boost::bind(&Foo::DoStuff, _1)); // How to bind the static funciton here
}
void AssignCallback(boost::function<void(int param)> doStuffHandler)
{
...
...
}
};
我以前使用以下语法将 boost::bind 与成员函数一起使用:
boost::bind(&Foo::NonStaticMember, this, _1, _2, _3, _4)
但这显然对于静态成员是不正确的。
你能向我解释如何使用 boost::bind 正确绑定类的静态成员函数吗?
它将像普通函数绑定一样完成。对于静态函数,您只需要使用其类名来识别编译器的函数并跳过 this 参数,因为静态 finctions 绑定到类而不是对象。下面是一个简单的例子:
#include <iostream>
#include <boost/function.hpp>
#include <boost/bind.hpp>
void test(boost::function<bool(int, int)> func)
{
std::cout<<"in test().n";
bool ret = func(10, 20);
std::cout<<"Ret:"<<ret<<"n";
}
class Test
{
public:
static bool test2(int a, int b)
{
std::cout<<"in test2().n";
return a>b;
}
};
int main()
{
test(boost::bind(&Test::test2, _1, _2));
return 0;
}
O/P:
in test().
in test2().
Ret:0
不应使用它,因为静态函数没有此指针。
int main()
{
test(boost::bind(&Test::test2, this, _1, _2));-----> Illegal
return 0;
}
Below error will occur:
techie@gateway1:myExperiments$ g++ boost_bind.cpp
boost_bind.cpp: In function âint main()â:
boost_bind.cpp:26: error: invalid use of âthisâ in non-member function
希望这会有所帮助。
你的代码是正确的。也许您遇到一些编译器问题?你能引用编译输出吗?
您也可以尝试使用 std::function 和 std::bind 代替。仅将提升标头替换为"功能"标头并写入
std::placeholders::_1
而不是
_1
相关文章:
- Boost 绑定和"result_type":不是成员,对 c++03 友好
- ROS 订阅回调 - 使用 boost::绑定成员函数
- 当Boost ::绑定模板函数时,模板参数扣除/替换失败
- 使用boost ::绑定结果作为参数
- boost ::绑定发送变量的回调args到回调函数
- 传递 boost::绑定参数作为参数
- boost::绑定在存储时不保存部分参数
- boost::绑定静态函数的参数
- 使用 boost :: 绑定将映射作为参数传递
- boost::与boost:asio绑定在一起.boost::绑定后续
- boost::与boost:asio绑定在一起.boost::绑定不起作用,从示例中复制
- Boost绑定和Boost函数,将带有参数的函数存储在向量中,然后执行它们
- boost::绑定具有默认值的成员函数
- boost::绑定到类成员函数
- boost::绑定重载函数
- boost绑定或返回常量的lambda函数
- boost::绑定内部副本
- boost::绑定模板化的函子
- 使用boost绑定成员函数
- boost::绑定动态参数