Originally Posted by
Codeplug
You can't use class member function as a for_each functor.
Should be able to do it using mem_fun_ref. I've done it before using different compilers MSVC++ 6.0 and MSVC .NET. Depending on the compiler I've used you need to do different things to get it to work. Under MSVC++ 6.0, the function being called needed to return a value and be non-const, i.e.:
Code:
#include <functional>
#include <algorithm>
#include <iostream>
#include <list>
class MyClass
{
public:
MyClass();
~MyClass();
std::list<int> l;
int Print(int i);
};
MyClass::MyClass()
{
for (int a=0;a<11;++a)
l.push_back(a);
std::for_each(l.begin(),l.end(),std::mem_fun_ref(MyClass::Print));
}
MyClass::~MyClass()
{
}
int MyClass::Print(int i)
{
std::cout<<i<<std::endl;
return 0;
}
int main(int argc,char* argv[])
{
MyClass mc;
return 0;
}
However, MSVC .NET wanted the called function to be a type void, const function:
Code:
#include <functional>
#include <algorithm>
#include <iostream>
#include <list>
class MyClass
{
public:
MyClass();
~MyClass();
std::list<int> l;
void Print(int i) const;
};
MyClass::MyClass()
{
for (int a=0;a<11;++a)
l.push_back(a);
std::for_each(l.begin(),l.end(),std::mem_fun_ref(MyClass::Print));
}
MyClass::~MyClass()
{
}
void MyClass::Print(int i) const
{
std::cout<<i<<std::endl;
}
int main(int argc,char* argv[])
{
MyClass mc;
return 0;
}
[edit]Added #include <algorithm> for the for_each function.[/edit]
[edit2]I just realized that this won't work because you are expecting an arugment to be passed to the Print function. You can pass an argument to the function also by using bind2nd as in:
Code:
std::for_each(l.begin(),l.end(),std::bind2nd(std::mem_fun_ref(MyClass::Print),1));
But as you see, you need a specific value to give as the second parameter, you can't really use what you were trying to print out the members of the list. You could however replace the for_each call with a call to copy and just to this:
Code:
std::copy(l.begin(),l.end(),std::ostream_iterator<int>(cout,"\n"))
[/edit2]