1

Here's my toy program. It fails to compile with error message " no operator << matches these operands". Any help will be appreciated.

struct foo {
    std::string name;
};

std::ostringstream& operator<<(std::ostringstream& os, const foo& info)
{
    os << info.name;
    return os;
}

void insert(const foo& info)
{
    std::ostringstream os;
    os << "Inserted here " << info;  // don't work here
}

int main()
{
    foo f1;
    f1.name = "Hello";
    insert(f1);

}
ark1974
  • 615
  • 5
  • 16

1 Answers1

5

The reason

os << "Inserted here " << info;

does not work is

os << "Inserted here "

returns a std::ostream&, not a std::ostringstream&.

Options:

  1. Change your function to be use std::ostream instead of std::ostringstream.

    std::ostream& operator<<(std::ostream& os, const foo& info) { ... }
    
  2. Change how you use it. Use

    os << "Inserted here ";
    os << info;
    

I strongly recommend using the first option.

R Sahu
  • 204,454
  • 14
  • 159
  • 270