boost::bind is extremely handy in a number of situations. One of them is to dispatch/post a method call so that an io_service will make the call later, when it can.
In such situations, boost::bind behaves as one might candidly expect:
#include <boost/asio.hpp>
#include <boost/bind.hpp>
boost::asio::io_service ioService;
class A {
public: A() {
// ioService will call B, which is private, how?
ioService.post(boost::bind(&A::B, this));
}
private: void B() {}
};
void main()
{
A::A();
boost::asio::io_service::work work(ioService);
ioService.run();
}
However, as far as I know boost creates a functor (a class with an operator()()) able to call the given method on the given object. Should that class have access to the private B? I guess not.
What am I missing here ?
boost::bind is a generalization of the standard functions std::bind1st and std::bind2nd. It supports arbitrary function objects, functions, function pointers, and member function pointers, and is able to bind any argument to a specific value or route input arguments into arbitrary positions.
If you instantiate the class Demo and you call $demo->myMethod(), you'll get a console: that console can access the first method writing a command like: > $this->myPublicMethod(); But you cannot run successfully the second one: > $this->myPrivateMethod();
You can call any member function via a pointer-to-member-function, regardless of its accessibility. If the function is private, then only members and friends can create a pointer to it, but anything can use the pointer once created.
Its through pointer-to-member-function, boost calls private functions. A member function of the class creates the pointer, and passes it to boost, and later on, boost uses that pointer to call the private function on an object of the class.
Here is one simple illustration of this basic idea:
class A;
typedef void (A::*pf)();
class A
{
public:
pf get_ptr() { return &A::B; } //member function creates the pointer
private:
void B() { cout << "called private function" << endl; }
};
int main() {
A a;
pf f = a.get_ptr();
(a.*f)();
return 0;
}
Output:
called private function
Though it doesn't use boost, but the basic idea is exactly this.
Note that only member functions and friend
can create pointer to private
member function. Others cannot create it.
Demo at ideone : http://ideone.com/14eUh
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With