Anmol Singh Jaggi
Anmol Singh Jaggi

Reputation: 8576

pretty printing nested arrays using templates

I have the following code to pretty-print arrays -:

// Print an array
// Does not work on nested arrays !
template<typename T1, size_t arrSize>
void printArray( T1 const( & arr )[arrSize], std::ostream& out = std::cout )
{
    out << "[";
    if ( arrSize )
    {
        for ( size_t it = 0; it != arrSize - 1; ++it )
        {
            out << arr[it] << ", ";
        }
        // Print the last element separately to avoid the extra characters following it.
        out << arr[arrSize - 1];
    }
    out << "]";
}

int arr[5][5];

int main()
{
    printArray( arr[0] );
    printArray( arr );
}

Output -:

[0, 0, 0, 0, 0]
[0x489040, 0x489054, 0x489068, 0x48907c, 0x489090]

Although it is working correctly in case of single-dimensional arrays, in case of multidimensional ones, the function prints the indivisual addresses of the arrays rather than their contents.

Is there any way to print generic multidimensional arrays using a single function call?

I am using GCC 4.9.2 with the -std=c++14 flag.

Upvotes: 2

Views: 583

Answers (1)

Jarod42
Jarod42

Reputation: 217810

You have to have one function for array, one for single element:

// Print a single element (use in array version)
template<typename T>
void printArray(T const &e, std::ostream& out = std::cout )
{
    out << e;
}

// Print an (nested) array
template<typename T1, size_t arrSize>
void printArray(T1 const(& arr)[arrSize], std::ostream& out = std::cout )
{
    out << "[";
    const char* sep = "";
    for (const auto& e : arr)
    {
        out << sep;
        printArray(e, out);
        sep = ", ";
    }
    out << "]";
}

Live Demo

Upvotes: 3

Related Questions