Boost logo

Boost :

From: Craig Hicks (hicks_at_[hidden])
Date: 2001-03-07 12:30:28


Hello

The following class, "os_iter", expounds upon the idea of
std::ostream_iterator,
which can be used with std::copy for writing to an output stream.

std::copy(x.begin(), x.end(), std::ostream_iterator<T>(os));
std::copy(x.begin(), x.end(), os_iter<T, FT, FI>(os));

The main template argument T of ostream_iterator is a type to print, and
operator << (etc)
must be defined for T.

The first template argument of os_iter is again T.

The second, FT, is a functional to print out T. It defaults to
"os_iter_def_ft", which just calls operator << (etc).
I have found this very useful because my compiler often cannot see the
declaration of operator << (etc)
from inside a template function. This is especially a problem when using
namespaces. Also, it allows custom
output formatting for that special occasion.

The third template parameter, FI. is used to print things around T, like a
line number (e.g., [3]) at the line start
and newline at the end. (The default functional "os_iter_def_fi" does
exactly this.)
This is more general than passing a single end of line character or string.

Here is typical output:
[0] 23
[1] 13
[2] 16
etc
where [n] is output by FI and 23, 13, 16 are output by FT.

Important details such as
value_type;
char_type;
traits_type;
ostream_type;
are all missing in this version, although I am able to use it successfully
without them.

If anyone has thoughts/code along similar lines please let me know.

Respectfully Yours

Craig Hicks
hicks_at_[hidden]

CODE FROM HERE::

#ifndef stdex_os_iterH
#define stdex_os_iterH

#include <iostream>

template <class T>
struct os_iter_def_ft
{
    typedef T value_type;
    void operator () (std::ostream& os, const typename T& t)
    {
        os << t;
    }
};

template <class T, class FT=os_iter_def_ft<T> >
struct os_iter_def_fi
{
    FT ft;
    int i;
    void operator () (std::ostream& os, const typename T& t)
    {
        os << "[" << i++ << "]";
        ft(os, t);
        os << std::endl;
    }
    os_iter_def_fi() : i(0) {}
};

template
    <class T,
    class FT=os_iter_def_ft<T>,
    class FI=os_iter_def_fi<T, FT> >
class os_iter
{
    std::ostream& os;
    FI fi;

 public:
    typedef T value_type;

    os_iter(std::ostream& _os) : os(_os) {}
    os_iter<T,FT,FI>& operator= (const T& value)
    {
        fi(os, value);
        return *this;
    }

    os_iter<T,FT,FI>& operator* () { return *this; }
    os_iter<T,FT,FI>& operator++ () { return *this; }
    os_iter<T,FT,FI>& operator++ (int) { return *this; }
};

#endif


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk