Home > Net >  Overloading std::array << operator
Overloading std::array << operator

Time:09-17

I'm having trouble trying to overload operator << for std::array. I tried doing it casual way as for all other collections:

std::ostream& operator<<(std::ostream& os, std::array<int> const& v1)
{
    for_each(begin(v1), end(v1), [&os](int val) {os << val << " "; });
    return os;
}

But the compiler expects me to add information about the array's size, which would not make it a general solution for any integer array. I know that if I wanted to make it for genaral type I would have to use templates, but for now I just want to make it for array of integers.

CodePudding user response:

Templates are not just for "general types". std::array is templated on both the type it holds as well as for the size of the array. So you need to template your operator if you want it to apply for any size int array:

template <std::size_t N>
std::ostream& operator<<(std::ostream& os, std::array<int, N> const& v1)
{
    for_each(begin(v1), end(v1), [&os](int val) {os << val << " "; });
    return os;
}
  • Related