gpt4 book ai didi

c++ - tr1::function 可以吞下返回值吗?

转载 作者:可可西里 更新时间:2023-11-01 16:38:27 25 4
gpt4 key购买 nike

boost::函数FAQ item 3专门针对我感兴趣的场景:

Why are there workarounds for void returns? C++ allows them! Void returns are permitted by the C++ standard, as in this code snippet:

void f();
void g() { return f(); }

This is a valid usage of boost::function because void returns are not used. With void returns, we would attempting to compile ill-formed code similar to:

int f();
void g() { return f(); }

In essence, not using void returns allows boost::function to swallow a return value. This is consistent with allowing the user to assign and invoke functions and function objects with parameters that don't exactly match.

不幸的是,这在 VS2008 中不起作用:

int Foo();
std::tr1::function<void()> Bar = Foo;

这会产生以以下内容开头的错误:

c:\Program Files\Microsoft Visual Studio 9.0\VC\include\xxcallfun(7) : error C2562: 'std::tr1::_Callable_fun<_Ty>::_ApplyX' : 'void' function returning a value

这是 VS2008 TR1 实现的失败吗?这在 VS2010 中有效吗? TR1 是否解决了此功能? C++0x 怎么样?

最佳答案

我相信 tr1 解决了这个问题。 N1836 (最新的 tr1 草案)说:

A function object f of type F is Callable for argument types T1, T2, ..., TN and a return type R, if, given lvalues t1, t2, ..., tNoftypesT1, T2, ..., TN,respectively,INVOKE(f, t1, t2, ..., tN)is well-formed([3.3]) and, if R is not void, convertible to R.

在您的示例中,R 是无效的,因此忽略了 Callable(可转换为 R)要求的最后一部分。

但是看起来 C++0x (C++11) 改变了规则。在 C++11 中,Callable 定义为 INVOKE(f, t1, t2, ..., tN, R),它在 [func.require] 中定义为要求INVOKE(f, t1, t2, ..., tN) 可隐式转换为 R,当 R 为 void 时也不异常(exception)。所以在 C++11 中,您的示例应该会失败。

关于c++ - tr1::function 可以吞下返回值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6628442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com