【问题标题】:How to use std::ref?如何使用 std::ref?
【发布时间】:2012-03-23 20:23:19
【问题描述】:

std::ref的正确使用方法是什么?我在 VS2010 中尝试了以下代码,但无法编译:

#include <vector>
#include <algorithm>
#include <iostream>
#include <functional>
using namespace std;
struct IsEven
{
    bool operator()(int n) 
    {
        if(n % 2 == 0)
        {
            evens.push_back(n);
            return false;
        }

        return true;
    }

    vector<int> evens;
};
int main(int argc, char **argv)
{
    vector<int> v;
    for(int i = 0; i < 10; ++i)
    {
        v.push_back(i);
    }

    IsEven f;
    vector<int>::iterator newEnd = remove_if(v.begin(), v.end(), std::ref(f));
    return 0;
}

错误:

c:\program 文件 (x86)\microsoft visual studio 10.0\vc\include\xxresult(28): error C2903: 'result' : 符号既不是类模板也不是函数模板

c:\program 文件 (x86)\microsoft visual studio 10.0\vc\include\xxresult(28):错误 C2143:语法错误:缺少 ';'在'之前

还有更多...

【问题讨论】:

  • 它使用 g++(4.6 和 4.8)编译。
  • @nabulke:即使在 C++11 中?我认为这应该可行..

标签: c++ stl c++11


【解决方案1】:

std::ref 的 Visual C++ 10.0 实现中存在一个或一组错误。

据报道,它已针对 Visual C++ 11 进行了修复;见我的earlier question about it

Microsoft 的 STL 如此回答:“我们已经修复了它,修复将在 VC11 RTM 中提供。(但是,修复没有进入 VC11 Beta。)”

【讨论】:

    【解决方案2】:

    我收到了与 VS2010 相同的编译错误,并通过从 std::unary_function 继承来纠正它:

    struct IsEven : std::unary_function<int, bool>
    

    我只考虑了这一点,因为result 出现在错误消息中。我只能猜测std::ref,在VS2010中,依赖于typedefs在unary_function中:

    template <class Arg, class Result>
      struct unary_function {
        typedef Arg argument_type;
        typedef Result result_type;
      };
    

    编辑:

    查看Cheers and hth. - Alf关于 VS2010 中的错误的回答。

    【讨论】:

    • 这不再是必要的了。提交错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-03
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 2021-08-29
    • 2014-01-22
    相关资源
    最近更新 更多