tags:

views:

145

answers:

3

Is there any way of creating a function that accepts any version of a given template class?

e.g. this works:

ostream& operator << (ostream &out,const Vector<int>& vec);

but this doesn't:

ostream& operator << (ostream &out,const Vector& vec);

Is it possible to get the second line to work somehow for any version of vector? e.g. vector<int> and vector<double> without having to write 2 separate functions?

Added to question:

I've made op<< a template function like you've suggested. In order to make it a friend function of the vector class I tried adding the following to the Vector class definition, but it didn't work:

friend ostream& operator << (ostream &out, const Vector<T>& vec);

any ideas what can be done to fix it?

+5  A: 

Sure, make it a template function:

template <typename T>
ostream& operator << (ostream &out,const Vector<T>& vec);
Alex Martelli
It's worth noting you'll have to most likely inline the function body as well
Todd Gardner
+2  A: 
template <class T>
ostream& operator << (ostream &out,const Vector<T>& vec);
jeffamaphone
+1  A: 

As already pointed out something like this should work:

template <typename T>
ostream& operator << (ostream &out,const Vector<T>& vec) {
    // body here
}

As for the friend requirement, that is most easily handled like this:

template <typename T>
ostream& operator << (ostream &out,const Vector<T>& vec) {
    vec.print_on( out );
    return out;
}

However, normally I would think of any output operator like this that requires access to the internals of the class to be showing you a mistake in your Vector class. It really only ought to need to use the public interface to do the display.

The other thing is that you might also want to template the output stream itself so that you can preserve its type:

template <typename O, typename C, typename T>
std::basic_ostream<O, C>& operator << (std::basic_ostream<O, C> &out,const Vector<T>& vec) {
    vec.print_on( out );
    return out;
}

The Vector's print_on can still use ostream.

KayEss
+1. You're right about operator<<() not usually needing to be a friend, too.
j_random_hacker