I’m trying to overload the insertion (<<) operator to output elements of an std::array. The following yields a compilation error:
// overload operator<< to display array objects of any type T and size N
template<typename T, int N>
std::ostream &operator<<(std::ostream &Output, const std::array<T,N> &Arr) {
for (const auto &Element: Arr)
Output << Element << " ";
return Output;
}
But the following works just fine (if I apply it to an array of, say, 5 elements):
// overload operator<< to display array objects of any type T and size 5
template<typename T>
std::ostream &operator<<(std::ostream &Output, const std::array<T,5> &Arr) {
for (const auto &Element: Arr)
Output << Element << " ";
return Output;
}
I’m aware that arrays need to know their size N at compile time, but doesn’t the template provide just that?
The error happens when I try, for instance, the following:
std::array<int,5> MyArr {1, 2, 3, 4, 5};
std::cout << "MyArr = " << MyArr;
>Solution :
The 2nd template argument of std::array is a size_t, not an int.
Also, return output; needs to be return Output; as C++ is case-sensitive.
// overload operator<< to display array objects of any type T and size N
template<typename T, size_t N>
std::ostream &operator<<(std::ostream &Output, const std::array<T,N> &Arr) {
for (const auto &Element: Arr)
Output << Element << " ";
return Output;
}