According to this answer, the correct way to overload output operator <<
for C-style arrays is this -:
#include <iostream>
using namespace std;
template <size_t arrSize>
std::ostream& operator<<( std::ostream& out, const char( &arr )[arrSize] )
{
return out << static_cast<const char*>( arr ); // use the original version
}
// Print an array
template<typename T1, size_t arrSize>
std::ostream& operator <<( std::ostream& out, const T1( & arr )[arrSize] )
{
out << "[";
if ( arrSize )
{
const char* separator = "";
for ( const auto& element : arr )
{
out << separator;
out << element;
separator = ", ";
}
}
out << "]";
return out;
}
int main()
{
int arr[] = {1, 2, 3};
cout << arr;
}
But I am still getting the compiler error
error: ambiguous overload for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'const char [2]')
for the out << "[";
and out << "]";
statements.
What is the correct way of doing this ?
enable_if_t
for the less handyenable_if
, so I guess it would be a better approach overall, even for the other question. – Marianomaribel