I have a class Foobar with string conversion operator:
#include <string>
class Foobar
{
public:
Foobar();
Foobar(const Foobar&);
~Foobar();
operator std::string() const;
};
I attempt to use it like this:
//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 an operator << for Foobar?. I don't see why that should be necessary since FooBar is converted to a string before being placed in the iostream, and std::string already has operator << defined.
So why this error?. What am I missing?
[Edit]
I just found out that if I changed the line the error occurs on, to this:
ss << "Foobar is: " << fb.operator std::string();
It compiles successfully. Urgh ...! Why can't the compiler do the automatic conversion (Foobar -> string) ?
What is the 'best practise' way to resolve this, so I don't have to use the ugly syntax above?