使用模板漂亮地打印嵌套数组

pretty printing nested arrays using templates

我有以下代码来漂亮地打印数组 -:

// 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 );
}

输出-:

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

虽然它在一维数组的情况下工作正常,但在多维数组的情况下,该函数打印数组的单独地址而不是它们的内容。

有什么方法可以使用单个函数调用来打印通用多维数组吗?

我正在使用带有 -std=c++14 标志的 GCC 4.9.2。

你必须有一个函数用于数组,一个用于单个元素:

// 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