CSpartan wrote:
I need to create a C++ function that works similar to 'cout'.
You should probably start with learning C++ first... 'cout' is not
a function, it is an object of a class (of 'std::ostream' or derived
thereof) and you apparently want to create a similar class. Note,
however, that this is done differently than you think: you are *not*
going to change 'std::ostream' or derive thereof (well, you might
derive from this class but only for convenient construction; see below)
but you want to derive a class from 'std::streambuf' and use it with
an 'std::ostream'.
I would like to have a function 'MyTextOut' that would accept the
following syntax
MyTextOut << "x = " << iX << " kg" ;
and outputs the concatenated string on a I/O channel defined by me.
IOStreams operate on external representations abstracted using the
class 'std::streambuf' (well, actually it is a class template called
'std::basic_streambuf' but you should probably ignore this detail for
noww and use the typedef 'std::streambuf' thinking of it as a normal
class). For handling output you want to override the virtual function
'sync()' and 'overflow()' which do similar but not identical operations.
In addition, you want to setup a buffer to avoid sending individual
characters. This looks something like this:
class io_channel_buf:
public std::streambuf
{
public:
io_channel_buf() { setp(m_buffer, m_buffer + s_size - 1); }
private:
int overflow(int c)
{
if (traits_type::eq_int_type(c, traits_type::eof()))
{
*pptr() = traits_type::to_char_type(c);
pbump(1);
}
return sync() == -1? traits_type::eof(): traits_type::not_eof(c);
}
int sync()
{
if (pbase() != pptr())
{
int rc = write(channel, pbase(), pptr() - pbase());
if (rc != pptr() - pbase())
return -1; // TODO: possibly deal with partially send buffers...
sep(m_buffer, m_buffer + s_size - 1);
}
return 0;
}
enum { s_size = 1024 };
char m_buffer[s_size];
};
The 'write()' function sends the characters to your I/O channel and
will probably be replaced by whatever approach is suitable to access
this I/O channel. You would then create an 'std::ostream' object which
internally uses this stream buffer for your stream object:
io_channel_buf MyTextBuf;
std::ostream MyTextOut(&MyTextBuf);
MyTextOut << whatever;
To avoid the two step construction of the output object, you might
derive from 'std::ostream' and setup the proper stream buffer in the
constructor of the derived class. You should, however, don't try to
temper with 'std::ostream's functios otherwise than this.
For more details on anything I have written, search for past articles
I have written in comp.lang.c++ or comp.lang.c++.moderated on similar
subjects...
--
<mailto:di***********@yahoo.com> <http://www.dietmar-kuehl.de/>
<http://www.eai-systems.com> - Efficient Artificial Intelligence