I am trying to use for_each to print a line vector in cout. However, when formulating the operator, I found that std::ostream::operator<<(const std::string &); not defined, leading to compiler errors. The following code illustrates the problem:
#include <iostream> #include <string> int main() { std::string message = "Hello World!\n"; // This works std::cout << message; // Compiler error std::cout.operator <<(message); }
I thought that both statements should look identical to the compiler. This is apparently not the case. So what is the difference?
solvable
As Tomalak and Prasun said, I needed to call this function:
std::ostream& operator<<(std::ostream&, const std::string&);
So the following sample will work:
#include <iostream> #include <string> int main() { std::string message = "Hello World!\n"; operator<<(std::cout, message); }
Regarding my original purpose (using for_each to print a line vector): It seems that it is better to use std::copy with std::ostream_iterator , as shown here: How do I use for_each to output to cout?
source share