I want to overload operator<< for arbitrary arrays, such that the code cout << my_arr would work. First I tried to overload the second parameter of operator<< on const T (&arr)[N], where T and N are template parameters. But testing the code revealed a side effect: const char[] also matches the type specification, and the new overload conflicts with the one defined in the stream class. Example code:
#include <cstddef>
#include <iostream>
template<typename T, std::size_t N>
std::ostream& operator<<(std::ostream& os, const T (&arr)[N])
{
/* do stuff */
return os;
}
int main()
{
std::cout << "noooo\n"; /* Fails: ambiguous overload */
}
Can such an array printing operator still be implemented?
void f(int arr[], size_t N){ cout<<arr; }arractually has the typeint*in that case, so it wouldn't match that overload.