问题描述
boost ::函数特别针对场景我对以下感兴趣:
The boost::function FAQ item 3 specifically addresses the scenario I am interested in:
void f();
void g() { return f(); }
这是
boost :: function的有效用法,因为void返回
不使用。使用void返回,我们
将尝试编译类似于以下内容的不成形的
代码:
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(); }
实质上,不使用void返回
允许boost :: function吞下
返回值。这与
一致,允许用户使用不完全匹配的
参数来分配和调用
函数和函数对象。
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.
$ b不幸的是,这在VS2008中不起作用:
Unfortunately, this doesn't work in 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?
Is this a failing of the VS2008 TR1 implementation? Does this work in VS2010? Does TR1 address this capability? How about C++0x?
推荐答案
我相信tr1解决了这个问题。 (最新的tr1草稿)说:
I believe tr1 addresses this issue. N1836 (the latest tr1 draft) says:
在你的例子中,R是void,因此 Callable
(可转换为R)的最后一部分要求被忽略。
In your example R is void, and so the last part of the requirements for Callable
(convertible to R) is ignored.
但是它看起来像C ++ 0x(C + + 11)更改规则。在C ++ 11中可调用
定义为 INVOKE(f,t1,t2,...,tN,R)
其在[func.require]中定义为要求 INVOKE(f,t1,t2,...,tN)
可隐式地转换为R,当R为空时。所以在C ++ 11中,你的示例应该会失败。
However it looks like C++0x (C++11) changes the rules. In C++11 Callable
is defined as INVOKE(f, t1, t2, ..., tN, R)
which is defined in [func.require] as requiring INVOKE(f, t1, t2, ..., tN)
to be implicitly convertible to R, with no exception for when R is void. So in C++11, your example should fail.
这篇关于tr1 :: function swallow可以返回值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!