Thanks for giving comments to the following.
Class1 { debug(std::ostream&){} };
int main() {
std::vector<Class1*> list1;
// some work to do
}
Target Platform:
- Platform(1): Win 7×64, VS2010
- Platform(2): Linux x32, g++ 4.4
Q: What should be the correct way to pass “std::cout” to following statement?
std::for_each(list1.begin(),
list1.end(),
"afunction(&Class1::debug, std::cout)");
I previously used “std::cout” inside the debug() function, but later consider to give flexibility for the output of debug message.
Edit: More information: if functor objects is the way to go, how should I implements the functor to cope with multiple classes (those classes have no relationship except the same “debug” function signature)?
Edit(2): Using “std::for_each”, is it possible to destroy all objects in list1 by invoking the corresponding destructor for each class directly? (e.g. for_each(l.begin(), l.end(), “Class::~Class1”);
Edit(3): As per “pmr” suggested, I make the statement as
std::for_each(l.begin(),
l.end(),
std::bind2nd(std::mem_fn(&Class1::debug), out) );
It compiles and run correctly on linux platform, but failed on VS2010, the code for Class1::debug is
void Class1::debug(const std::ostream& out)
{
out << "some text" << someVar << "some text" << std::endl;
}
The VS error msg is
error C2678: binary ‘<<‘ : no operator found which takes a left-hand operand of type ‘const std::ostream’ (or there is no acceptable conversion)
Any cue?
[Closed]
I now implemented the overloaded operator << for my classes, and the use of debug print function is closed. Thanks very much for all hints given.
Since you are using g++ 4.4 you can’t use lambda expressions which would be the first choice (later versions support them, MSVC does as well).
So you need a functor. A functor is a function object, that is a class (or struct) that implements
operator(). Like this:Use like this: