I have overloaded operator<<
to print a built-in array const int (&arr)[N]
:
template <size_t N>
std::ostream& operator<<(std::ostream& os, const int (&arr)[N])
{
os << "{ ";
bool first{true};
for (int i : arr)
{
os << (first ? "" : ", ") << i;
first = false;
}
return os << " }";
}
I can use it to print a const int (&)[5]
array to std::cout
:
int arr[3][5] = {{3, 4, 6, 1, 1}, {6, 3, 4, 5, 1}, {6, 1, 2, 3, 3}};
for (const auto& subarr : arr) { std::cout << subarr << "\n"; }
// Outputs:
//
// { 3, 4, 6, 1, 1 }
// { 6, 3, 4, 5, 1 }
// { 6, 1, 2, 3, 3 }
However, when I try to print the same array via a std::copy
to std::ostream_iterator<const int (&)[5]>
, I just get the array address printed out:
std::copy(std::cbegin(arr), std::cend(arr),
std::ostream_iterator<const int (&)[5]>{std::cout, "\n"});
// Outputs:
//
// 0x7ffec4f84db0
// 0x7ffec4f84dc4
// 0x7ffec4f84dd8
I suppose the array is decaying to a pointer at the ostream_iterator
end. If so, is there a way to avoid that?
[Demo] for a working version.
There are many questions in this site regarding array-to-pointer decay, but I haven't seen one that was helping with this case.
Actually, this answer says:
[...] you can also prevent decay in your original version of
f
if you explicitly specify the template agumentT
as a reference-to-array type
f<int (&)[27]>(array);
But that doesn't seem to be happening when constructing the ostream_iterator
.