Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Overloading insertion operator for std::array

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading