home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!darwin.sura.net!wupost!cs.utexas.edu!sun-barr!ames!agate!dog.ee.lbl.gov!network.ucsd.edu!deadmin.ucsd.edu
- From: rmr@deadmin.ucsd.edu (Robert Rother)
- Newsgroups: comp.lang.c++
- Subject: Help needed overloading "<<" with templates?
- Message-ID: <1912@deadmin.ucsd.edu>
- Date: 21 Jul 92 06:06:34 GMT
- Sender: rmr@deadmin.ucsd.edu
- Organization: UCSD Division of Engineering
- Lines: 104
-
- Ok I give up. I have more or less copied the template code for the
- Array class in Lippman's 2nd Edition C++ Primer (pg 380). Using Turbo
- C++ 3.1 for windows I have two problems with the overloading of the
- "<<" operator. First as noted before it won't compile without the
- addition of an "&" and second the call to the print member works while
- the use of the overloaded operator "<<" just prints a hex address.
- It's obvious to me that my overloaded operator is not being used by why
- is the mystery.
-
- My sanity is more important than my ego at the moment so any help would
- be more than appreciated!
-
- Robert Rother
- rmr@deadmin.ucsd.edu
-
- P.S. I have no problem with the same code fragment minus the templates.
- -----------------------------------------------------------------------
- #include <assert.h>
- #include <iostream.h>
-
- const int ArraySize = 12;
-
- template <class Type> class Array;
-
- template <class Type> ostream &
- operator<<(ostream&, Array<Type>&);
-
- template <class Type>
- class Array {
- public:
- Array(int sz = ArraySize);
- ~Array() { delete [] ia; }
- void print(ostream& = cout);
- private:
- void init(const Type *, Type);
- int size;
- Type *ia;
- };
-
- template <class Type>
- Array<Type>::Array(int sz)
- {
- size = sz;
-
- init(0, sz);
- }
-
- template <class Type>
- void
- Array<Type>::init(const Type *array, int sz)
- {
- ia = new Type[size = sz];
- assert(ia != 0);
-
- for (int ndx = 0; ndx < size; ndx++)
- ia[ndx] = (array != 0) ? array[ndx] : 0;
- }
-
- template <class Type> ostream&
- operator << ( ostream& os, Array<Type>& ar)
- {
- ar.print(os);
- return(os);
- }
-
- template <class Type>
- void Array<Type>::print(ostream& os)
- {
- const int linelen = 12;
-
- os << "(" << size << ")<";
- for (int ndx = 0; ndx < size; ndx++) {
- if ((ndx % linelen) == 0 && ndx)
- os << "\n\t";
- os << ia[ndx];
- if ((ndx % linelen) != linelen - 1 && ndx != size - 1)
- os << ", ";
- }
- os << " >\n";
- }
-
- template <class Type>
- void try_it(Array<Type>& ar)
- {
- cout << "Start\n";
-
- ar.print(cout);
-
- cout << "Middle\n";
-
- // Note: the book shows the following but it wouldn't compile:
- // *** cout << ar << endl;
- cout << &ar << endl;
-
- cout << "Done!" << endl;
- }
-
- main()
- {
- Array<int> iA;
-
- try_it(iA);
- return(0);
- }
-