如何使用std::ref

How to use std::ref?

本文关键字:ref std 何使用      更新时间:2023-10-16

使用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 files(x86)\微软visual studio10.0\vc\include\xxresult(28):错误C2903:"result":符号既不是类模板,也不是函数模板

c: \program files(x86)\微软visual studio10.0\vc\include\xxresult(28):错误C2143:语法错误:缺少";"在'<'之前

再加上一些。。。

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

据报道,它已经为Visual C++11修复;看看我之前的问题。

微软的STL如此回答:"我们已经修复了它,该修复将在VC11 RTM中提供。(然而,该修复没有进入VC11测试版。)"

我在VS2010中收到了相同的编译错误,并通过从std::unary_function:继承进行了更正

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

我只是考虑到result出现在错误消息中。我只能猜测,在VS2010中,std::ref取决于unary_function:中的typedef

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

编辑:

请参阅Cheers和hth-中的答案Alf关于VS2010中的错误。