T
Trevor
Hello,
Please bear with me, I am trying to learn C++. I am implementing some
error/debug functions which format a message and output it to a C++ stream.
I would like to design it using one low level function which accepts a
"generic C++ stream" as an argument (cerr, cout, ofstream, etc). I have
tried to make the parameter a const ostream&, but when I plug in cerr or
cout I get a compiler error. What am I doing wrong?
// The low level function just formats some message and outputs it to
"stream".
void _output(const ostream& stream, const char* reason, int error)
{
ostringstream message;
// ... do some formatting
if (stream == cerr)
cerr << message << endl;
else if (stream == cout)
cout << message << endl;
}
// the high level functions just direct the output to a different stream
void outputerr(const char* reason, int error)
{
// do something special for errors
_output(cerr, reason, error);
}
void outputcmt(const char* reason, int error)
{
// do something special for comments
_output(cout, reason, error);
}
void outputwrn(const char* reason, int error)
{
// do something special for warnings
_output(cout, reason, error);
}
The compiler error is:
binary '<<': no operator found which takes a left-hand operand of type
'const std:stream' (or there is no acceptable conversion)
on the line of code:
"stream << message.str().c_str() << endl" // compiler error is in _output()
Please bear with me, I am trying to learn C++. I am implementing some
error/debug functions which format a message and output it to a C++ stream.
I would like to design it using one low level function which accepts a
"generic C++ stream" as an argument (cerr, cout, ofstream, etc). I have
tried to make the parameter a const ostream&, but when I plug in cerr or
cout I get a compiler error. What am I doing wrong?
// The low level function just formats some message and outputs it to
"stream".
void _output(const ostream& stream, const char* reason, int error)
{
ostringstream message;
// ... do some formatting
if (stream == cerr)
cerr << message << endl;
else if (stream == cout)
cout << message << endl;
}
// the high level functions just direct the output to a different stream
void outputerr(const char* reason, int error)
{
// do something special for errors
_output(cerr, reason, error);
}
void outputcmt(const char* reason, int error)
{
// do something special for comments
_output(cout, reason, error);
}
void outputwrn(const char* reason, int error)
{
// do something special for warnings
_output(cout, reason, error);
}
The compiler error is:
binary '<<': no operator found which takes a left-hand operand of type
'const std:stream' (or there is no acceptable conversion)
on the line of code:
"stream << message.str().c_str() << endl" // compiler error is in _output()