Problem with overloading the << operator in a Template.

This is a discussion on Problem with overloading the << operator in a Template. within the C++ Programming forums, part of the General Programming Boards category; For my program, I'm trying to overload the << operator and make it a friend of the Template, but I'm ...

  1. #1
    Registered User
    Join Date
    Dec 2010
    Posts
    19

    Problem with overloading the << operator in a Template.

    For my program, I'm trying to overload the << operator and make it a friend of the Template, but I'm getting an error when I try to build the program. My book does not at all cover how to do this, so what I am doing is based off some stuff I read online, but obviously I'm doing something wrong. Here's some of my code:

    Code:
    template <typename T>
    class Array
    {
      friend ostream &operator<<  <T>(ostream &, const Array<T> &);
    : public
     // other function prototypes
    };
    //Further in the file
    
    ostream &operator<<(ostream &out, const Array<T> &arr)
    {
       //function body
    }

    When I made a little driver for my program and built it, I got "error C2065: 'T' : undeclared identifier" and "warning C4552: '<<' : operator has no effect; expected operator with side-effect." I'm assuming that once I get the first error fixed, the second one will go away. The first error points me to the function header of the ostream operator, so something must be wrong with it. Like I said, my book is not helpful for this problem and I haven't been able to figure it out by looking it up online. It's probably something very simple, but I just can't see it. Can someone help me out?

  2. #2
    Registered User C_ntua's Avatar
    Join Date
    Jun 2008
    Posts
    1,853
    It helps pointing out at what line the error is. I guess you need
    Code:
    template <typename T>
    Array<T>::ostream &operator<<(ostream &out, const Array<T> &arr)
    {
       //function body
    }

  3. #3
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    4,402
    Actually, that would be:

    Code:
    template <typename T>
    std::ostream &operator<<(std::ostream &out, const Array<T> &arr)
    {
       //function body
    }
    Soma

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. operator new overloading and template functions
    By krappa in forum C++ Programming
    Replies: 40
    Last Post: 05-28-2008, 09:29 AM
  2. Replies: 7
    Last Post: 11-10-2007, 05:17 AM
  3. template/operator overloading ambigous on gcc
    By xErath in forum C++ Programming
    Replies: 2
    Last Post: 06-16-2005, 08:40 PM
  4. Operator overloading in template classes
    By moejams in forum C++ Programming
    Replies: 5
    Last Post: 07-21-2003, 06:16 PM
  5. Replies: 2
    Last Post: 01-04-2003, 03:35 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21