0

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.

5
  • How about just using std::vector<int>? I doubt that you pursue performance of allocation that std::array is for, so it would be the easiest to use a dynamic-size array Commented Aug 25, 2021 at 11:23
  • @AlexeyLarionov I know that I can do it that way for vector, I'm just curious how to do it for std::array, as I just started learning about this collection Commented Aug 25, 2021 at 11:25
  • 2
    every array of a different size is a different type so you have to use templates Commented Aug 25, 2021 at 11:25
  • 1
    std::array<int> is not a type (as std::array<int, 4> would be). You need to use a template instead of a normal function. Commented Aug 25, 2021 at 11:26
  • 3
    BTW: IMO for (const auto & val : v1) { os << val << " "; } would be more readable. Commented Aug 25, 2021 at 11:30

1 Answer 1

5

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.