Assuming you only mean c-style arrays (where the size is part of the type definition), and not a pointer, you could roll out the following:
#include <iostream>
using namespace std;
template<typename T, size_t N>
ostream& operator<< (ostream& outA, T (& arr)[N]) {
outA << arr[0];
T (&next)[N-1] = reinterpret_cast<T(&)[N-1]>(arr[1]);
outA << next;
return outA;
}
template<typename T>
ostream& operator<< (ostream& outA, T (& arr)[1]) {
outA << arr[0];
return outA;
}
int main() {
int a[] = {1, 2, 3, 4};
cout << a;
return 0;
}
Even though it works, it has all the overhead of recursion for a very simple task. Not to mention that ugly reinterpret_cast
just so I could treat the tail of the array as an array of a smaller size...
And also like NathanOliver said, you'd stamp out a separate function for each step in the recursion.
So in closing, I sincerely hope your question is purely academic.
A less awful implementation can be achieved if you use operator<<
as only a wrapper that extracts the array size, and then calls the real function.
template<typename T>
void printArr(ostream& outA, T *a, size_t n) {
if (n > 0) {
outA << *a;
printArr(outA, a + 1, n - 1);
}
}
template<typename T, size_t N>
ostream& operator<< (ostream& outA, T (& arr)[N]) {
printArr(outA, arr, N);
return outA;
}
In this version: there only two function instantiations per invocation, there is no ugly casting, and the actual recursive call looks like a traditional recursive call.