boost::bind 如何调用私有方法?
boost::bind 在许多情况下都非常方便。其中之一是调度/发布方法调用,以便 io_service 稍后在可能的情况下进行调用。
在这种情况下,boost::bind 的行为正如人们所期望的那样:
#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();
}
但是,据我所知,boost 创建了一个能够在给定对象上调用给定方法的函子(一个带有运算符()()的类)。该类应该有权访问私有 B 吗?我想不是。
我在这里缺少什么?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以通过成员函数指针调用任何成员函数,无论其可访问性如何。如果函数是私有的,那么只有成员和朋友可以创建指向它的指针,但是一旦创建,任何东西都可以使用该指针。
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.
boost通过成员函数指针调用私有函数。类的成员函数创建指针,并将其传递给 boost,随后 boost 使用该指针调用该类对象上的私有函数。
以下是这一基本思想的简单说明:
输出:
虽然没有使用boost,但基本思想正是如此。
请注意,只有成员函数和
friend
可以创建指向private
成员函数的指针。其他人无法创建它。ideone 演示:http://ideone.com/14eUh
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:
Output:
Though it doesn't use boost, but the basic idea is exactly this.
Note that only member functions and
friend
can create pointer toprivate
member function. Others cannot create it.Demo at ideone : http://ideone.com/14eUh