据我所知:void (A::*p)() = &A::test_func;
意味着p
是指向成员函数void A::test_func()
的指针,std::mem_fn(...)
可用于包装指向成员函数的指针。
但是在下面的代码片段中,我无法翻译void (Handler::*)()
和Handler::*member_fn
的意思。
class Handler;
std::pair<boost::shared_ptr<Handler>, void (Handler::*)()> cb = job_queue.sync_pop();
void (Handler::*member_fn)() = cb.second;
(cb.first.get()->*member_fn)();
它的意思正是您在第一段中描述的内容:
// cb contains a shared pointer to an instance of Handler and a member function of Hander
std::pair<boost::shared_ptr<Handler>, void (Handler::*)()> cb = job_queue.sync_pop();
// assign the member function stored in cb.second to a local variable
void (Handler::*member_fn)() = cb.second;
(cb.first.get()->*member_fn)(); // call the function stored in member_fn on
// the object held by cb.first
如果这还不够干净,你可以在这里找到一个使用标准库类的最小示例,它做同样的事情
class Handler;
std::pair< // a pair consisting of first and second
boost::shared_ptr<Handler>, // first - a shared pointer to Handler object
void (Handler::*)()> // second - a pointer to the member function of Handler class
cb = job_queue.sync_pop(); // sync_pop() returns such pair, stores it in cb variable
// varaible "member_fn" stores pointer to a member function from the pair
void (Handler::*member_fn)() = cb.second;
// cb.first.get()-> - dereference pointer to Handler object, say handlerObj
// *member_fn - dereference the pointer to member function
// (cb.first.get()->.*member_fn())() - invoke the function stored in member_fn variable
// on handlerObj (just like handlerObj.member_fn();)
(cb.first.get()->*member_fn)();
这将更具可读性:
auto pair = job_queue.sync_pop();
auto function = std::bind(pair.second, pair.first.get());
function();