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.
-
if i create an array like this int array[5], can i overload the << operator so i can print the rllements insise array?Seeven– Seeven2019-05-13 14:42:59 +00:00Commented May 13, 2019 at 14:42
2 Answers
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
5 Comments
auto& would simplify the return type.auto abuse!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