我有这个代码:
#include <iostream>
#include <functional>
struct A
{
int operator()(int i) const {
std::cout << "F: " << i << std::endl;
return i + 1;
}
};
int main()
{
A a;
std::tr1::function<int(int)> f = std::tr1::ref(a);
std::cout << f(6) << std::endl;
}
目的是通过 reference_wrapper 传递仿函数对象,以避免无用的复制构造函数调用。 我期望以下输出:
F: 6
7
它可以与 GCC >= 4.4.0、Visual Studio 2008 以及通过将 std::tr1 命名空间替换为 boost 的 boost 一起正常工作。它仅不适用于新的 Visual Studio 2010 Express Beta 2 和 Release Candidate。
这个新的 C++ 特性在 vs2010 中有问题吗? 或者代码中有什么错误或误用?
最佳答案
我想我找到了原因。这就是 TR1 3.4/2
说 result_of<T(A1, A2, ..., AN)>::type
, 用于确定 reference_wrapper<T>::operator()
的返回类型:
The implementation may determine the type member via any means that produces the exact type of the expression f(t1, t2, ..., tN) for the given types. [Note: The intent is that implementations are permitted to use special compiler hooks —end note]
然后是第 3 段:
If F is not a function object defined by the standard library, and if either the implementation cannot determine the type of the expression f(t1, t2, ..., tN) or if the expression is ill-formed, the implementation shall use the following process to determine the type member:
- If F is a possibly cv-qualified class type with no member named
result_type
or iftypename F::result_type
is not a type:
- If N=0 (no arguments), type is void.
- If N>0, type is
typename F::template result<F(T1, T2,..., TN)>::type
错误消息是尝试这些回退的产物。为 result_type
提供类型定义至 int
我认为它应该有效。请注意,在 C++0x
中,这是不同的。它不依赖 result_type
或 result
模板,因为它可以使用 decltype
.
如果有<functional>
它在 C++0x 模式下使用 MSVC10 失败,我会说它闻起来像一个错误。但也许其他人知道发生了什么。它可能(但不保证)与 <tr1/functional>
一起工作在 C++0x 模式下,如果该 header 选择采用 decltype
方式而不是 ::result_type
.我会 typedef result_type
- 这样我认为无论 tr1
是否有效,它都应该始终有效使用 header 或 c++0x
header 。
另请注意 boost::tr1
在其文档中说它不支持函数调用运算符(但它仅支持隐式转换为 T&
)。
关于c++ - Visual Studio 2010 和 std::function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2425277/