Thread: ostream operator<< () overload problems

  1. #1
    Registered User
    Join Date
    Jun 2006
    Posts
    1

    Red face ostream operator<< () overload problems

    I am using gcc on cygwin to compile the following code;

    Code:
    template<class C>
    ostream & operator<<(ostream & os, const vector<C> & v) {
    
    	os << "Vector of size " << (int)v.size() << " contains :" << endl << " | ";
    
    	for ( typename vector<C>::const_iterator iter = v.begin();
    			iter != v.end();
    			++iter ) {
    
    		os << *iter << " | ";
    	}
    
    	os << endl;
    
    	return os;
    }
    Code:
    #include "utilities.h"
    #include	<iostream>
    #include	<vector>
    
    int main() {
    
    	std::vector<int> v(10,10);
    
    	std::cout << v << std::endl;
    
    	return 0;
    }
    when I try to link I get this error:

    undefined reference to `std::basic_ostream<char, std::char_traits<char> >& operator<< <int>(std::basic_ostream<char, std::char_traits<char> >&, std::vector<int, std::allocator<int> > const&)'

    any ideas? thanks

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    It would be pretty difficult to get something like that to work. Create an inserter for your class, and then you'd want to access the object you placed in the vector and insert that. Visually this is something like...
    Code:
    class C {
       int foo;
    public:
       explicit C(int foo_in = 0): foo(foo_in) {  }
       ~C() {  }
    
       friend std::ostream &operator << (std::ostream &outs, const C &c) {
          return outs << c.foo;
       }
    };
    
    std::vector<C> vec;
    vec.push_back(C(42));
    std::cout << vec[0] << "\n";
    Last edited by whiteflags; 06-24-2006 at 04:45 PM.

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    That code should work fine.

    Just make sure that the first bit of code you posted is in the header file. Templated classes and functions must be defined in the header, not the source file (or the source file must be included).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C Pointers Problems
    By mhelal in forum C Programming
    Replies: 8
    Last Post: 01-10-2007, 06:35 AM
  2. String Manipulation problems -_-
    By Astra in forum C Programming
    Replies: 5
    Last Post: 12-13-2006, 05:48 PM
  3. Rendering problems (DirectX?)
    By OnionKnight in forum Tech Board
    Replies: 0
    Last Post: 08-17-2006, 12:17 PM
  4. C++ Operator Overload Question
    By cworld in forum C++ Programming
    Replies: 0
    Last Post: 03-25-2002, 07:17 PM
  5. Problem with code on oper. overload.
    By Unregistered in forum C++ Programming
    Replies: 2
    Last Post: 03-19-2002, 09:44 AM