4

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?

oompahloompah
  • 9,087
  • 19
  • 62
  • 90

1 Answers1

6

Foobar fb is not converted to a string before being placed into your stream. There is no requirement that arguments to the << operator must be strings.

You should either convert it to a string manually

ss << "Foobar is: " << std::string(fb);

Or define an operator<< for Foobar.

Defining an operator<< would be the smart way to go, and there's no reason you couldn't just call your string conversion in your operator<< code.

ProdigySim
  • 2,825
  • 1
  • 21
  • 17