Templatizing Overloaded Operators

Hi, LeafyCircuits here (•‿•)

After recently learning about templates, I began an experiment, but so far, that isn't turning out well.
I'm trying to templatize a custom function that overloads the << operator.

Here's the code:
1
2
3
4
5
6
7
8
9
10
template <typename T>
ostream& operator << (ostream &out, vector<T> &vec)
{
         vector<T>::iterator itr=vec.begin();
         for (;itr!=vec.end();itr++)
         {
             out << *itr;      //edit: was 'cout', now 'out'
         }
         return out;
}


I want to be able to output the contents of any vector by simply calling
cout << somevector << endl;

However, when I try to compile, I get the following errors:
Line 4: expected `;' before "itr"
Line 5: `itr' undeclared (first use this function)


But, I know for a fact that I have correct syntax on this line:
vector<T>::iterator itr=vec.begin();

So here's my question: Can you templatize an operator this way? If not, can you templatize operators in general?




I'm terribly new to the forums, so constructive criticism is greatly appreciated. Thank you for reading my plight. (•‿•)
Last edited on
closed account (Dy7SLyTq)
isnt operator<< ie no space?
The compiler doesn't know that vector<T>::iterator is naming a type. It could be any kind of member or static function/variable. It won't know what it is until it tries to instantiate the template.

So you need to give it a hint by using the typename keyword:

 
typename vector<T>::iterator itr = vec.begin();



Although... if you are using C++11, the better way to do this would be to just use the auto keyword and let the compiler figure it out based on the context:

 
auto itr = vec.begin();



constructive criticism is greatly appreciated.


Your code is pretty good. The only thing I can mention is you're not being const correct. The << operator is not modifying the vector, so it should be taking a const vector:

 
ostream& operator << (ostream &out, const vector<T> &vec)


But this of course means you'll also have to use a const_iterator instead of a regular iterator:

 
typename vector<T>::const_iterator itr = vec.begin();


Or... again... if you're using C++11, just use auto.
I don't understand the following part:
1
2
3
4
for (;itr!=vec.end();itr++)
         {
             cout << *itr; // why cout and why not out << *itr;
         }
Thanks a ton, Disch :)

@abhishekm71
whoops, I didn't mean that to be 'cout', thanks for spotting that.
Topic archived. No new replies allowed.