/* -*- Mode: C++ -*-
 *
 * $Header: /home/gene/library/website/docsrc/cppi/src/RCS/print-list.cxx,v 395.1 2008/04/20 17:25:49 gene Exp $
 *
 * Copyright (c) 2006 Gene Michael Stover.  All rights reserved.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301
 * USA
 */

/*
 * Print two sequences of integers.
 * The sequences are of different types.  One is a list.
 * The other, a vector.
 * This demonstrates two function templates & a functor.
 * All are seamlessly instantiated without requiring that
 * the caller know the exact type of the output stream
 * std::cout.
 */

#include "this.hxx"

namespace {
  using std::endl;
  using std::for_each;
  using std::setw;
  
  template<typename T, class OutputStream>
  class Printer {
  public:
    Printer (OutputStream &strm) {
      m_strm = &strm;
    }

    void operator() (T const &thing) {
      (*m_strm) << setw(4) << thing;
    }

  private:
    OutputStream *m_strm;
  };

  template<class Sequence, class OutputStream>
  void
  PrintSequence (Sequence const &seq, OutputStream &strm) {
    for_each (seq.begin (),
              seq.end (),
              Printer<typename Sequence::value_type, OutputStream> (strm));
    strm << endl;
  }

  template<class Sequence>
  void
  FillSequence (Sequence *seq) {
    int i;

    for (i = 0; i < 10; ++i) {
      seq->push_back (i);
    }
  }

  template<class Sequence>
  void
  Run (Sequence *seq) {
    FillSequence (seq);
    PrintSequence (*seq, std::cout);
  }
};

int
main ()
{
  using std::cout;
  int rc = 0;
  std::list<int> a;
  std::vector<int> b;

  Run (&a);
  Run (&b);
  return rc == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
}

/* --- end of file --- */
