std ::函数为sighandler_t [英] std::function as sighandler_t
问题描述
如何指定lambda,std :: bind结果或任何其他std :: function作为unix信号函数的参数?
How to specify lambda, std::bind result or any other std::function as argument for unix signal function?
我正在尝试以下
std::function<void(int)> handler1 = std::bind(&cancellation_token::cancel, &c);
std::function<void(int)> handler2 = [&c](int) { c.cancel(); };
但是它不起作用,因为两者都
but it doesn't work, because both
handler1.target<void(int)>()
和
handler2.target<void(int)>()
return null
如果我使用自由函数指针初始化处理程序,它将起作用
It works if I initialize handler with free function pointer
void foo(int) { ... }
std::function<void(int)> handler = foo;
但这绝对没用.我需要捕获一些局部变量,因此需要bind或lambda.
but this is absolutely useless. I need to capture some local variables, so I need either bind or lambda.
实际上,我知道为什么它不起作用.文档说,如果target_type() == typeid(T)
,target
函数将返回指向存储函数的指针,否则返回空指针.我不知道如何使它工作.
Actually I understand why it doesn't work. Documentation says that target
function returns a pointer to the stored function if target_type() == typeid(T)
, otherwise a null pointer. I don't understand how to make it work.
有什么建议吗?
推荐答案
由于它是由bind
或具有捕获数据的lambda构造的,因此您无法将其转换为自由函数,因为target
函数由typeid
起作用,std::function
会将其保存在运行时中,而不是将function
用作模板的类型T
.对于std::bind
,它将是某种库类型,对于lambda,它将是某种未命名类型.
Since it's constructed by bind
, or lambda with captured-data, you cannot convert it to free function, since target
function works by typeid
, std::function
saves it in runtime, not for type T
, with which function
is templated. For std::bind
it will be some library-type and for lambda it will be some unnamed type.
这篇关于std ::函数为sighandler_t的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!