2

I have a custom Vector template class which basically looks like this:

template <typename T>
class Vector{
...
friend ostream& operator<<(ostream& os, const Vector&<T> rop);
};

After that, I have defined a class Person. I would like to specialize the operator<< for a Vector of Persons (or Vector).

What would be the best way to do it? Thanks in advance!

zunnzunn
  • 366
  • 1
  • 5
  • 12

1 Answers1

1

Just implement a specialized version of your Vector for the type Person

class Person
{
};

template <typename T>
class Vector{
friend ostream& operator<<(ostream& os, const Vector<T> &rop);
};

template<>
class Vector<Person>
{
    friend ostream& operator<<(ostream& os, const Vector<Person> &rop);
};

If you have other methods in Vector<T> which you don't want to have in Vector<Person>, just leave them out in the specialization.

Running example

Edit: To answer the question in the comment: Yes there is a different way, just define the operator outside of your class like this:

template <typename T>
class Vector{
};

template<typename T>
std::ostream& operator<<(std::ostream &os, Vector<T> &prop)
{
    return os;
}
template<>
std::ostream& operator<<(std::ostream &os, Vector<Test> &prop)
{
    return os;
}

And specialize a version for the Vector<Person> type.

ckruczek
  • 2,361
  • 2
  • 20
  • 23
  • That is a quite straightforward solution! Thank you! However, if I want my Vector to be exactly the same as the generic Vector, (except everything specialized for Person ofc) is there a shorter way to do it, besides just copying everything again and writing "Person" instead of "T"? – zunnzunn Mar 25 '17 at 14:36