数组的重载输出运算符

Overloading output operator for arrays

本文关键字:运算符 输出 重载 数组      更新时间:2023-10-16

根据这个答案,对 C 样式数组的输出运算符<<重载的正确方法是这样 -:

#include <iostream>
using namespace std;
template <size_t arrSize>
std::ostream& operator<<( std::ostream& out, const char( &arr )[arrSize] )
{
    return out << static_cast<const char*>( arr ); // use the original version
}
// Print an array
template<typename T1, size_t arrSize>
std::ostream& operator <<( std::ostream& out, const T1( & arr )[arrSize] )
{
    out << "[";
    if ( arrSize )
    {
        const char* separator = "";
        for ( const auto& element : arr )
        {
            out << separator;
            out << element;
            separator = ", ";
        }
    }
    out << "]";
    return out;
}
int main()
{
    int arr[] = {1, 2, 3};
    cout << arr;
}

但是我仍然收到编译器错误

error: ambiguous overload for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'const char [2]')  

用于out << "[";out << "]";语句。

正确的方法是什么?

问题是打印字符数组的operator<<的标准重载是这样的:

template< class CharT, class Traits >
basic_ostream<CharT,Traits>& operator<<( basic_ostream<CharT,Traits>& os,
                                         const char* s );

因此,当您提供您的:

template <size_t arrSize>
std::ostream& operator<<( std::ostream& out, const char( &arr )[arrSize] )

这将是模棱两可的:我们有两个不同的函数模板,具有相同的转换序列,其中任何一个都不比另一个更专业。

但是,由于您希望您的版本仅调用原始版本,因此根本没有理由提供您的版本。只需使用 SFINAE 使您的"通用"阵列打印机不接受char

// Print an array
template<typename T1, size_t arrSize, 
         typename = std::enable_if_t<!std::is_same<T1,char>::value>>
std::ostream& operator <<( std::ostream& out, const T1( & arr )[arrSize] )
{ /* rest as before */ }