I’m trying to do it this way:
template <typename T>
ostream &operator<<(ostream &os, T &arr)
{ /*...*/ }
But can T represent an array? Is it correct to overload the << operator for an array?
EDIT:
According to Kerrek SB’s advice, here is my implementation for <<:
template <typename T, unsigned int N>
ostream &operator<<(ostream &os, const T (&arr)[N])
{
int i;
for(i = 0; i < N; i++)
os << arr[i] << " ";
os << endl;
return os;
}
Is my implementation right? I got a compilation error.
You could do this:
This works only for compile-time arrays, of course. Note that you are not allowed to instantiate this template when
Tis a built-in type or a type in thestdnamespace!Probably best to make this inline if possible, since you’ll cause a separate instantiation for every
N. (The pretty printer has an example of this.)You will notice, though, that the blanket template introduces an ambiguity, because
os << "Hello"now has two possible overloads: the template matchingconst char (&)[6], and the (non-template) overload for the decay-to-pointerconst char *, which both have identical conversion sequences. We can resolve this by disabling our overload for char arrays:In fact, to be even more general you can also make the
basic_ostreamparameters template parameters:In view of the fact that
Tmust be a user-defined type, you could even replaceis_same<T, char>withis_fundamental<T>to get a bit more checking (but users still must not use this for arrays of standard library types).