【发布时间】:2021-07-14 13:29:41
【问题描述】:
考虑以下无法编译的代码:
#include <mutex>
#include <functional>
class t{
std::mutex m;
};
std::function<void(t test)> func = [](t test) {return;};
产生以下错误:
错误:从 '
' 转换为非标量类型 'std::function ' 请求
你能解释一下为什么这个转换不起作用吗?
PS : 现场示例:https://godbolt.org/z/7se8crf41
【问题讨论】:
-
a
std::mutex既不能复制也不能移动(传播到t),您的意思是使用std::unique_lock<std::mutex>还是引用t? -
@PeterT 这解决了这个问题,但你如何解释错误信息?
-
我认为
t不可复制或不可移动是根本原因,但当您认为auto f = [](t test) {return;}; f({});没问题时,我不明白这一点是如何解释错误的 -
@463035818_is_not_a_number
std::function的要求之一是函数类型和参数通过std::is_invokable即not the case here -
@PeterT 你能给我指个参考吗?我没有找到那个信息。同时有一个答案正确解释了为什么 OPs 代码失败,但是你的评论让我很好奇,我发现它不仅仅是构造函数 godbolt.org/z/6qooa6o3h (注意:答案不适用的不同示例)