C++ 使用模板打印嵌套数组

C++ 使用模板打印嵌套数组,c++,arrays,templates,multidimensional-array,pretty-print,C++,Arrays,Templates,Multidimensional Array,Pretty Print,我有以下代码来打印数组-: // 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 ) {

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

// 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 );
}
//打印数组
//不适用于嵌套数组!
模板
void printary(T1常量(&arr)[arrSize],std::ostream&out=std::cout)
{

out您必须为数组设置一个函数,为单个元素设置一个函数:

// 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 << "]";
}
//打印单个元素(在数组版本中使用)
模板
void printary(T const&e,std::ostream&out=std::cout)
{

out可以使用
std::array
,也可以省略“if(arrSize)”条件