Re: endl like behavior
schwehr@gmail.com wrote:
Hi All,
I am trying to creat a class that that acts much like cerr and am
having trouble figuring out if it is possible to use std::end with my
class to designate then end of a group of items.
I presume you mean std::endl, as in your subject line. Here are two
examples of how to make an iomanip:
// Output carriage return and line feed
inline std::ostream& crlf( std::ostream &os )
{
return os << "\r\n";
}
// Output a number to a stream in hexidecimal format
// without altering the state of the stream.
class Hex
{
typedef unsigned ui32;
typedef int i32;
std::ostringstream m_oss;
public:
Hex( const ui32 &i, const i32 width=8 )
{
m_oss << "0x" << std::hex << std::setfill('0')
<< std::setw(width) << i;
}
Hex( const Hex &h )
{
m_oss.str( h.m_oss.str() );
}
friend std::ostream& operator<<( std::ostream &os, const Hex &h )
{
return os << h.m_oss.str();
}
};
They can be used like this:
std::ostringstream os;
os << "The number is" << Hex( 1789 ) << crlf;
I'd like this class
to look as close to simple cerr usage as possible to make it easy to
use. Appologies if this is a dumb question :) Is there a relatively
simple way to do this?
Yes. Use (or contain) a std::ostringstream or std::ofstream object or
have your class inherit from std::ostream. The latter option should not
generally be preferred.
I am not sure what exactly is going on in the
templates in the ostream header.
That is why you should generally use the facilities provided by the
library rather than trying to reinvent the wheel.
Cheers! --M