Reputation: 446
I want to bind a static member function to a boost::function using boost::bind. The following is an example of what I want to do (not working).
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)
{
...
...
}
};
I have previously used boost::bind with member functions using this syntax:
boost::bind(&Foo::NonStaticMember, this, _1, _2, _3, _4)
But this is obviously not correct for a static member.
Can you please explain to me how to correctly bind a static member function of a class using boost::bind?
Upvotes: 3
Views: 4357
Reputation: 387
It will be done as you do for normal functions binding. For static function you just need to use its class name for to recognize the function by the compiler and skip the this argument since static finctions are bound to class not to the object. Below is a simple example:
#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
You should not use this as static functions dont have this pointer.
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
Hope this will help. :-)
Upvotes: 4
Reputation: 8218
Your code is correct. Maybe you experience some compiler issue? Can you cite the compilation output?
You can also try using std::function and std::bind instead. Only replace boost headers with "functional" header and write
std::placeholders::_1
instead of
_1
Upvotes: 1