c++ - Visual Studio 2010 和 std::function

标签 c++ visual-studio-2010 functional-programming c++11 functor

我有这个代码:

#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/2result_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 if typename 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_typeresult模板,因为它可以使用 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/

相关文章:

c++ - 是否可以将固定大小的数组作为 unordered_map 键

c++ - 在代码生成后更改 llvm::Function 签名,在最后一个 CreateRet 之前

c++ - bash 脚本在使用 popen() 时不将返回码返回给调用 C++ 程序

c++ - 如何调试 Visual Studio 环境变量的使用?

c++ - 为什么 long long 值与 8 字节边界对齐?

.net - global.asax 在本地计算机上工作,但在我发布到服务器后不起作用

python - 函数式编程 Python : smallest number divisible by each of the numbers 1 to 20

c# - 将进程内 COM 服务器对象添加到 C# 应用程序

functional-programming - 为什么在 OCaml 中出现 "Reference to undefined global ` Moduletest'"?

string - haskell-需要整数的字符串