problem with STL mem_fun_ref and internal use

What am I doing so wrong as to make this code fail:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <functional>
#include <algorithm>
#include <vector>

using namespace std;

struct Y
{
   Y(vector<int> const& vref):
   mVec(vref)
   {}

   void print(int const& cref) const
   {
      cout << cref << endl;
   }

   void out()
   {
      for_each(mVec.begin(), mVec.end(), mem_fun_ref(&Y::print));
   }

   private:
      vector<int> mVec;
};

int main()
{
   vector<int> v;
   v.push_back(1);
   v.push_back(2);
   v.push_back(3);
   v.push_back(4);
   
   Y y(v);
   y.out();

   return 0;
}


How should it be done with mem_fun_ref?
mem_fun_ref returns a function object which has the following function call operator:

 
RetType operator()( ObjectInstance&, const ParameterType& ) const;


ie, two parameters, but std::for_each() only passes one parameter.

Personally I'd use boost::bind or boost::lambda to solve this problem.

1
2
3
4
5
std::for_each( mVec.begin(), mVec.end(), boost::bind( &Y::print, this, _1 ) );

// or

std::for_each( mVec.begin(), mVec.end(), std::cout << boost::lambda::_1 );


Or for this specific case you can also use ostream iterators.
How could for_each know on what object to dereference pointer...
So: throw away mem_fun_ref in this case...

But, I keep on staring at this:

1
2
3
4
5
void findEmptyString(const vector<string>& strings)
{
   vector<string>::const_iterator it = find_if(strings.begin(), strings.end(),
   mem_fun_ref(&string::empty));
}

Why is that supposed to work then?
find_if() passes each element to operator(). ie, a "this" pointer, which is what
the underlying binder expects.
Topic archived. No new replies allowed.