2012-03-06 45 views
9

什麼是使用std::ref的正確方法?我試着按照VS2010的代碼,它不會編譯:如何使用std :: ref?

#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 Studio 10.0 \ VC \ \包括xxresult(28 ):錯誤C2903: '結果':符號既不是類模板,也不是一個函數模板

C:\程序文件(86)\微軟的Visual Studio 10.0 \ VC \包括\ xxresult(28):錯誤C2143:語法錯誤:缺少';'前「<」

加上一些更多...

+0

它與編譯g ++(4.6和4.8)。 – kennytm 2012-03-06 11:04:03

+0

@nabulke:即使在C++ 11中?我認爲這應該工作.. – Asha 2012-03-06 11:05:35

回答

8

std::ref的Visual C++ 10.0實現中存在一個錯誤或一組錯誤。

據報道,它已被修復爲Visual C++ 11;看我的earlier question about it

STL微軟正是如此回答:「我們已經定了,而且弄不好還會在VC11 RTM可用的(但是,修復並沒有進入VC11 Beta版。)。」

4

我收到相同的編譯錯誤與VS2010和由std::unary_function繼承糾正它:

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

我只考慮這是由於result出現在錯誤信息中。我只能猜測,std::ref,在VS2010中,unary_function依賴於typedef S:

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

編輯:關於VS2010的錯誤從Cheers and hth. - Alf

見的答案。

+0

這應該不再是必要的。提交一個錯誤。 – pmr 2012-03-06 11:15:37

+0

編譯一次..有趣.. – Asha 2012-03-06 11:15:48