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

标签 c++ c++11 tr1 boost-function

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/

相关文章:

c++ - unordered_multimap::equal_range 慢

c++ - STL TR1 为 gcc 提供文档

c++ - 分解来自文件c++的输入

c++ - 从元组中提取 vector

c++ - 如何检测用户是否按下了 Ctrl-Alt-Del 或 Alt-Tab 以便我可以最小化我的程序?

c++ - 如何编写替换链式方法调用的可变参数方法?

c++ - tr1/正则表达式的问题。打印相反的结果

c++ - 如何将 DLL 链接到我的主项目? (获取 Unresolved external 错误)

c++ - std::is_assignable 和 const 指针对象

c++ - 定义模板化运算符重载时出错