how to format this generic code

Hi,

the following code snippet is trying to print a std::array container generically. It is printing every element consecutively like the following

1 2 3 4 5 6 7 8 9 10 11 12

I couldn't find a way on how to format. I'll appreciate if someone could shed a light on how to print every row in a line.
1 2 3
4 5 6
7 9 9
10 11 12

Thanks
Sabetay

#include <iostream>
using namespace std;
#include <type_traits>
#include <array>

using TCount0 = array<int, 3>;
using TCount1 = std::array<TCount0, 2>;
using TCount2 = std::array<TCount1, 2>;

template<class T, std::size_t N>
struct is_array<std::array<T, N>> : std::true_type {};

template <typename T>
void PrintArray(T& A) {
if (is_array<T>::value)
for(auto& e : A)
PrintArray(e);
}
template<>
void PrintArray(int& e)
{
cout << e << " ";
}
int main()
{
TCount2 Cnt = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
PrintArray(Cnt);
}
> the following code snippet is trying to print a std::array container generically
but only works if T=int

> how to print every row in a line.
you want a different element separator based on the element type
¿why is the same function?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <array>
#include <iomanip>

// print_irpl: print array with one inner most row per line
template < typename T, std::size_t N > // overload for simple arrays
std::ostream& print_irpl( const std::array<T,N>& array, int width, std::ostream& stm = std::cout )
{
    // innermost row: print the row in a line
    for( const T& v : array ) stm << std::setw(width) << v << ' ' ;
    return stm << '\n' ;
}

template < typename T, std::size_t N, std::size_t M > // overload for nested arrays
std::ostream& print_irpl( const std::array< std::array<T,M>, N>& array, int width, std::ostream& stm = std::cout )
{
    // print each sub-array
    for( const auto& subarray : array ) print_irpl( subarray, width, stm ) ;
    return stm ;
}

int main()
{
    using A1 = std::array<int,3>;
    using A2 = std::array<A1,2>;
    using A3 = std::array<A2,2>;

    const A3 a3 { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
    print_irpl( a3, 2 ) << '\n' ;

    using A4 = std::array<A3,3> ;
    const A4 a4 { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
                  11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
                  21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 };
    print_irpl( a4, 2 ) << '\n' ;
}

http://coliru.stacked-crooked.com/a/2c48a9ac93fa009b
Topic archived. No new replies allowed.