1

I have a question. in C++, can I overload the operator<<, so I can print an array of a given size, without the need of a class? I managed to print an array but only if i made that array a member of a class.

1
  • if i create an array like this int array[5], can i overload the << operator so i can print the rllements insise array? Commented May 13, 2019 at 14:42

2 Answers 2

4

Yes, absolutely you can do that.

Just go ahead and define an overload of that operator to take whatever you want. It does not need to be of class type.

So, something like this:

template <typename T, std::size_t N>
std::ostream& operator<<(std::ostream& os, const T (&arr)[N])
{
   for (const auto& el : arr)
      os << el << ' ';

   return os;
}

(live demo)

However, I caution against going overboard with this; other programmers using your code probably won't expect it, and there aren't many other non-class types that don't already have overloads like this (consider that all the integers, char types, bool and pointers already "do something" when streamed).


Full demo code, for posterity:

#include <iostream>
#include <cstddef>

template <typename T, std::size_t N>
std::ostream& operator<<(std::ostream& os, const T (&arr)[N])
{
   for (const auto& el : arr)
      os << el << ' ';

   return os;
}

int main()
{
    int array[] = {6,2,8,9,2};
    std::cout << array << '\n';
}

// Output: 6 2 8 9 2
Sign up to request clarification or add additional context in comments.

5 Comments

i think the for iterates over elements in the array, but i can't quite understand the syntax "const auto : arr"
@Seeven It's a range-based for loop
I think auto& would simplify the return type.
@Ayxan It would obfuscate it without meaningfully simplifying it. auto abuse!
@Seeven You can do whatever you like inside the operator; point is how to declare the overload itself.
1

Another way of doing this is with std::copy and std::ostream_iterator

#include <iostream>
#include <algorithm>
#include <iterator>
#include <cstddef>

template <typename T, auto N>
auto& operator<<(std::ostream& os, T(&arr)[N])
{
  std::copy(std::cbegin(arr), std::cend(arr), std::ostream_iterator<T>(os, " "));
  return os;
}

int main()
{
    int array[] = { 6, 2, 8, 9, 2};
    std::cout << array << '\n';
}

// Output: 6 2 8 9 2

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.