There is no match for "operator <<" in std :: operator << [With _Traits = std :: char_traits <char>]
I have a Foobar class with a string conversion operator:
#include <string> class Foobar { public: Foobar(); Foobar(const Foobar&); ~Foobar(); operator std::string() const; }; I am trying to use it as follows:
// C ++ source file
#include <iostream> #include <sstream> #include "Foobar.hpp" int main() { Foobar fb; std::stringstream ss; ss << "Foobar is: " << fb; // Error occurs here std::cout << ss.str(); } Do I need to explicitly create a <<operator for Foobar ?. I do not understand why this is necessary, since FooBar is converted to a string before being placed in iostream, and std :: string already has a <<defined operator.
So why is this a mistake ?. What am I missing?
[change]
I just found out that if I changed the line, an error would occur on it:
ss << "Foobar is: " << fb.operator std::string(); It compiles successfully. Urh ...! Why can't the compiler perform automatic conversion (Foobar -> string)?
What is the best way to solve this problem, so I don't need to use the ugly syntax above?
Foobar fb is not converted to a string before being placed into your stream. It is not necessary that the arguments in the <operator must be strings.
You must either convert it to a string manually
ss << "Foobar is: " << std::string(fb); Or define the <<operator for Foobar.
Defining the <operator will be a smart way, and there is no reason why you could not just invoke the string conversion in your operator <<code.