Search code examples
c++stdtr1mem-fun

How do I use std::tr1::mem_fun in Visual Studio 2008 SP1?


The VS2008 SP1 documentation talks about std::tr1::mem_fun.

So why, when I try and use std::tr1::mem_fun, why do I get this compile error?:

'mem_fun' : is not a member of 'std::tr1'

At the same time, I can use std::tr1::function without problems.

Here is the sample code I am trying to compile, which is supposed to call TakesInt on an instance of Test, via a function<void (int)>:

#include "stdafx.h"
#include <iostream>
#include <functional>
#include <memory>

struct Test { void TakesInt(int i) { std::cout << i; } };

void _tmain() 
{
    Test* t = new Test();

    //error C2039: 'mem_fun' : is not a member of 'std::tr1'
    std::tr1::function<void (int)> f =
        std::tr1::bind(std::tr1::mem_fun(&Test::TakesInt), t);
    f(2);
}

I'm trying to use the tr1 version of mem_fun, because when using std::mem_fun my code doesn't compile either! I can't tell from the compiler error whether the problem is with my code or whether it would be fixed by using tr1's mem_fun. That's C++ compiler errors for you (or maybe it's just me!).


Update: Right. The answer is to spell it correctly as mem_fn!

However when I fix that, the code still doesn't compile.

Here's the compiler error:

error C2562: 
'std::tr1::_Callable_obj<_Ty,_Indirect>::_ApplyX' :
  'void' function returning a value

Solution

  • Change it to this:

    std::tr1::function<void (int)> f =
        std::tr1::bind(std::tr1::mem_fn(&Test::TakesInt), t, std::tr1::placeholders::_1);
    f(2);
    

    The binder requires the int argument. So you have to give it a placeholder which stands for the integer argument that the generated function object needs.

    Btw: I'm not sure whether you already know this or not. But you don't need that mem_fn for this. Just change it to

    std::tr1::function<void (int)> f =
        std::tr1::bind(&Test::TakesInt, t, std::tr1::placeholders::_1);
    f(2);