ccoder83 ccoder83 - 1 year ago 89
C++ Question

Passing a C++ Member Function Pointer to an STL Algorithm

I have a member function as follows:

class XYZ{
float function(float x);
float m_DensityMin;
float m_DensityMax;

Now, I'm trying to transform a
std::vector<float> foo
using the
STL algorithm by passing the member function
, and storing the resulting values in a vector

If I use the function as a global function, with random data that should denote the member variables of the class, it works fine.

However, as the function requires the use of member variables
of the class, I need to use it as a member function. This is what I've tried:

std::transform(foo.begin(), foo.end(), bar.begin(), &XYZ::function);

but I end up with the error in VS2010:

error C2065: term does not evaluate to a function taking 1 arguments

As far as I can tell I'm passing only 1 argument. Any pointers?
Here's a similar question, I've tried with std::mem_fun, as std::mem_fn is not available to me, but to no avail.

Answer Source

std::mem_fun itself only povides a wrapper for a member function, so that one will be invoked in the context of the first argument passed to its operator(). Having said that, you need to bind the proper instance of XYZ prior to passing the function object to the std::transform algorithm:

XYZ xyz;

std::transform(foo.begin(), foo.end(),
               std::bind1st(std::mem_fun(&XYZ::function), &xyz));
//                  ~~~~~~^      ~~~~~~^                  ~~~^


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download