使用`std :: function< void(...)>`来调用非void函数 [英] Using `std::function<void(...)>` to call non-void function
问题描述
过去我使用 std :: function
,大致如下:
std :: function< void(int)> func = [](int i) - > int {return i; };
基本上,我这样做是因为我想将不同的函数对象存储在 std :: function
,但我不想限制这些函数的返回类型。由于这似乎工作,我去与它。但我不相信它是安全使用,我没有能够找到它的任何文档。有谁知道这种用法是否合法?或者更一般地,可以安全地分配给 std :: function
?
Edit
为了说明,我关心的问题是lambda函数返回 int
func
声明为返回类型 void
。我不知道这是否可以,特别是一旦调用 func()
。
您的代码具有未定义的行为。它可能或可能不工作,你所期望的。它有未定义行为的原因是因为20.8.11.2.1 [func.wrap.func.con] / p7:
>需要:
F
应为CopyConstructible
。对于参数类型ArgTypes
和返回类型
,
f
应为可调用(20.8.11.2) / code>。
对于 f
类型 R
, f
必须返回可隐式转换为 std :: function
( void
)。 int
不能隐式转换为 void
。
我希望你的代码可以在大多数实现上工作。但是,至少有一个实现( libc ++ ),它无法编译:
test.cpp:7:30:error:没有可行的从'int(int)'到'std :: function< void(int)>'的转换
std: :function< void(int)> ff = f;讽刺的是,这种行为的根本原因源自于 $〜
$〜
< //stackoverflow.com/q/5931214/576911\">其他SO问题。
另一个问题提出了 std的问题:: function
用法。该问题的解决方案涉及在编译时执行强制执行 Requires:子句。相比之下,此问题的问题的解决方案是禁止执行强制执行 Requires:子句。
A while ago I used std::function
pretty much like this:
std::function<void(int)> func = [](int i) -> int { return i; };
Basically, I did this because I wanted to store different function objects in a std::function
, but I didn't want to restrict the return types of these functions. Since this seemed to work, I went with it. But I'm not convinced that it is safe to use, and I haven't been able to find any documentation on it. Does anyone know whether this usage is legitimate? Or more generally, what the rules are for the object which can safely be assigned to a std::function
?
Edit
For clarification, the issue I'm concerned with is that the lambda function returns an int
, while func
is declared with return type void
. I'm not sure if this is OK, especially once a call to func()
is made.
解决方案 Your code has undefined behavior. It may or may not work as you expect. The reason it has undefined behavior is because of 20.8.11.2.1 [func.wrap.func.con]/p7:
Requires: F
shall be CopyConstructible
. f
shall be Callable (20.8.11.2) for argument types ArgTypes
and return type R
.
For f
to be Callable for return type R
, f
must return something implicitly convertible to the return type of the std::function
(void
in your case). And int
is not implicitly convertible to void
.
I would expect your code to work on most implementations. However on at least one implementation (libc++), it fails to compile:
test.cpp:7:30: error: no viable conversion from 'int (int)' to 'std::function<void (int)>'
std::function<void(int)> ff = f;
^ ~
Ironically the rationale for this behavior stems from another SO question.
The other question presented a problem with std::function
usage. The solution to that problem involved having the implementation enforce the Requires: clause at compile time. In contrast, the solution to this question's problem is forbidding the implementation from enforcing the Requires: clause.
这篇关于使用`std :: function< void(...)>`来调用非void函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!