11

What is the correct way to use std::ref? I tried following code in VS2010 and it doesn't compile:

#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;
}

Errors:

c:\program files (x86)\microsoft visual studio 10.0\vc\include\xxresult(28): error C2903: 'result' : symbol is neither a class template nor a function template

c:\program files (x86)\microsoft visual studio 10.0\vc\include\xxresult(28): error C2143: syntax error : missing ';' before '<'

Plus some more...

2
  • It compiles with g++ (both 4.6 and 4.8). Commented Mar 6, 2012 at 11:04
  • @nabulke: even in C++11? I thought this should work.. Commented Mar 6, 2012 at 11:05

2 Answers 2

9

There is a bug or set of bugs in Visual C++ 10.0 implementation of std::ref.

It has reportedly been fixed for Visual C++ 11; see my earlier question about it.

STL at Microsoft answered thusly: "We've already fixed it, and the fix will be available in VC11 RTM. (However, the fix didn't get into the VC11 Beta.)"

Sign up to request clarification or add additional context in comments.

Comments

4

I recieved the same compilation error with VS2010 and corrected it by inheriting from std::unary_function:

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

I only considered this due to result appearing in the error message. I can only guess that std::ref, in VS2010, depends on the typedefs in unary_function:

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

EDIT:

See answer from Cheers and hth. - Alf regarding bug in VS2010.

1 Comment

This should not be necessary anymore. File a bug.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.