[英]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正确绑定类的静态成员函数吗?
它将像常规函数绑定一样完成。 对于静态函数,您只需要使用其类名即可由编译器识别该函数,并跳过此参数,因为静态函数是绑定到类的,而不是绑定到该对象的。 下面是一个简单的示例:
#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代替。 仅将boost头替换为“ functional”头并写入
std::placeholders::_1
代替
_1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.