delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2001/10/08/05:34:17

Message-ID: <3BC16F90.A6FE66E3@falconsoft.be>
Date: Mon, 08 Oct 2001 11:19:12 +0200
From: Tim Van Holder <tim DOT vanholder AT falconsoft DOT be>
Organization: Anubex (www.anubex.com)
X-Mailer: Mozilla 4.78 [en] (X11; U; Linux 2.2.16-3 i686)
X-Accept-Language: en, nl-BE, nl
MIME-Version: 1.0
Newsgroups: comp.lang.c++,comp.os.msdos.djgpp
Subject: Re: More out from "cout"....
References: <9pque5$eui$1 AT tron DOT sci DOT fi>
Lines: 53
NNTP-Posting-Host: 194.78.64.238
X-Trace: 1002532812 reader1.news.skynet.be 36476 194.78.64.238
X-Complaints-To: abuse AT skynet DOT be
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

Traveler wrote:
> 
> 
> template <int n>
> ostream&    operator<<(ostream& output,int (&table)[n])
> {
>     unsigned long    length = sizeof(table)/sizeof(table[0]);

Since you know the type here, you culd use sizeof(int) instead
of sizeof(table[0]).
Of course, since you also know the array is of length n, this
entire construct is superfluous.

>     for(unsigned long index = 0;index < length;index++)
>        output << '[' << table[index] << ']';

Hmm - I'm not sure I want array elements shown inside [].
A more logical way to do it is to separate them by ", ".
Also, you can probably templatize the array type as well.

template <typename T, size_t N>
ostream&
operator<<(ostream& out, T (&array)[N])
{
  for (size_t i = 0; i < n; ++i) {
    if (i > 0)
      out << ", ";
    out << array[i];
  }
  out.flush();
}


Of course, if you're going to screw around with templates,
you really should be using STL vectors instead:

template <typename T, typename A>
std::ostream&
operator<<(std::ostream& out, const std::vector<T, A>& array)
{
std::vector<T, A>::const_iterator first = array.begin();
std::vector<T, A>::const_iterator last  = array.end();
std::vector<T, A>::const_iterator i;
  for (i = first; i != last; ++i) {
    if (i != first)
      out << ", ";
    out << (*i);
  }
  out.flush();
}

or something like it anyway (not sure if this function needs
to include the allocator used by the vector as template arg).

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019