Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::tr1::mem_fn return type

Tags:

c++

std

tr1

I want to put the result of this:

std::tr1::mem_fn(&ClassA::method);

Inside a variable, what is the type of this variable ?

That will look something like this:

MagicalType fun = std::tr1::mem_fn(&ClassA::method);

Also, what is the result type of std::tr1::bind ?

Thank you !

like image 482
Tarantula Avatar asked Aug 02 '10 17:08

Tarantula


2 Answers

The return types of both std::tr1::mem_fn and std::tr1::bind are unspecified.

You can store the result of std::tr1::bind in a std::tr1::function:

struct ClassA { 
    void Func() { }
};

ClassA obj;
std::tr1::function<void()> bound_memfun(std::tr1::bind(&ClassA::Func, obj));

You can also store the result of std::tr1::mem_fn in a std::tr1::function:

std::tr1::function<void(ClassA&)> memfun_wrap(std::tr1::mem_fn(&ClassA::Func));
like image 115
James McNellis Avatar answered Nov 01 '22 15:11

James McNellis


The return type of mem_fn and bind is unspecified. That means, depending on the arguments a different kind of object is returned, and the standard doesn't prescribe the details how this functionality must be implemented.

If you want to find out what the type is in a particular case with a particular library implementation (for theoretical interest, I hope), you can always cause an error, and get the type from the error message. E.g:

#include <functional>

struct X
{
    double method(float);
};

int x = std::mem_fn(&X::method);

9 Untitled.cpp cannot convert 'std::_Mem_fn<double (X::*)(float)>' to 'int' in initialization

In this case, note that the type's name is reserved for internal use. In your code, you shouldn't use anything with a leading underscore (and a capital letter).

In C++0x, I suppose the return type would be auto :)

auto fun = std::mem_fn(&ClassA::method);
like image 3
UncleBens Avatar answered Nov 01 '22 15:11

UncleBens