Seeven
Seeven

Reputation: 46

Overloading operator<< for array without the need of a class

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.

Upvotes: 1

Views: 83

Answers (2)

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 30005

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

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385405

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

Upvotes: 4

Related Questions