在ROS中有一个函数叫做NodeHanle::subscribe(Args...):NodeHandle::subscribe。这使您可以将 PRIVATE 成员函数作为回调传递。
但是,当我自己尝试时(使用 std::bind 传递私有成员函数),我的编译器总是失败并抱怨Foo::foo() is a private member function. 当我Foo::foo转为公共职能时,一切都恢复正常。
template<typename T>
void getWrapper1(void(T::*fn)(int), T *t) {
return [&](int arg) {
std::cout << "process before function with wrapper" << std::endl;
(t->*fn)(arg);
std::cout << "process after function with wrapper" << std::endl;
};
}
void getWrapper2(std::function<void(int)> fn) {
return [=](int arg) {
std::cout << "process before function with wrapper" << std::endl;
fn(arg);
std::cout << "process after function with wrapper" << std::endl;
}
}
class Foo {
private:
void foo(int a) {
std::cout << __FUNCTION__ << a << std::endl;
}
}
int main(int argc, char** argv) {
Foo foo_inst;
auto func1 = getWrapper1(&Foo::foo, &foo_inst); // fail because foo is private
auto func2 = getWrapper2(std::bind(&Foo::foo, &foo_inst, std::placeholders::_1)); // fail because foo is private
func1(1);
func2(2);
return 0;
}
从这个答案,使用std::function也可以传递私有成员函数。但是我尝试过的不同。
值得一提的是,在getWrapper2我使用[=]而不是[&]因为使用[&]可能会导致段错误。为什么它必须是“价值捕获”?
平台:GCC 5.4.0、c++14、ubuntu16.04