【发布时间】:2017-11-20 12:09:51
【问题描述】:
我正在尝试使用std::bind 将成员函数用作termios.h 标头中sigaction 的回调。我了解成员函数需要特别注意,并已阅读并遵循示例 here 和 here,但没有这样的运气。
因为我可以通过静态函数,我想如果我让函数保持静态,添加第二个变量作为指向自身的指针(this),我会很好,但没有这样的运气:
// In SerialListener.h
static void callback(int status, SerialListener *ptr);
// In the serial listener constructor
// Set callback
auto cb = std::bind(&SerialListener::callback, std::placeholders::_1, this);
sigAct_.sa_handler = cb;
但是报错如下:
error: cannot convert ‘std::_Bind<void (*std::_Placeholder<1>, SerialListener*))(int, SerialListener*)>’ to ‘__sighandler_t {aka void (*)(int)}’ in assignment sigAct_.sa_handler = cb;
我还尝试了第二个示例中没有静态实现的变体:
// In SerialListener.h
void callback(int status);
// In the serial listener constructor
// Set callback
auto cb = std::bind(&SerialListener::callback, this, std::placeholders::_1);
sigAct_.sa_handler = cb;
产生...
error: cannot convert ‘std::_Bind<std::_Mem_fn<void (SerialListener::*)(int)>(SerialListener*, std::_Placeholder<1>)>’ to ‘__sighandler_t {aka void (*)(int)}’ in assignment sigAct_.sa_handler = cb;
错误看起来很相似,看起来它不能将绑定隐式转换为它需要的处理程序,但是当我从输入类型和返回类型的角度来看它时,它应该可以工作。我错过了什么?
【问题讨论】:
-
@NageG -
static类/结构的成员更像是普通函数:不绑定到特定对象并且不知道this;this对待非静态成员。 -
Bind 返回一种闭包object。它不能转换为函数指针。您不能将
__sighandler_t的另一个参数偷偷带入调用中。 -
sigaction不是来自signal.h? -
我也试过在静态函数中使用
this和一个void指针,不应该this隐式转换为一个void指针,然后我可以将它转换回SerialListener*?我也试过了,但没有用,但我不明白为什么。 -
据我所知,没有办法将“用户数据”指针放入信号处理程序,您需要使用从处理程序可见的变量。