重载输出运营商数组 [英] Overloading output operator for arrays

查看:129
本文介绍了重载输出运营商数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据这个答案,重载输出操作符的正确方法<< 对于C风格的数组是这样的 - :

According to this answer, the correct way to overload output operator << for C-style arrays is this -:

#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;
}

但我仍然得到编译器错误

But I am still getting the compiler error

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

出&LT;&LT; [; 出&LT;&LT; ]; 语句。

什么是这样做的正确方法是什么?

What is the correct way of doing this ?

推荐答案

问题是的 运营商的LT;&LT; ,打印的字符数组是这个:

The problem is the standard overload for operator<< that prints a character array is this one:

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

所以,当你提供你的:

So when you provide yours:

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

这将是暧昧:我们有相同的转换序列,两者都不比其他更专业的两个不同的函数模板。

That's going to be ambiguous: we have two different function templates with identical conversion sequences, neither of which is more specialized than the other.

不过,既然你想你的版本只是调用原来,实在没有理由提供您的版本都没有。只是让你的通用阵打印机不接受字符使用SFINAE:

However, since you want your version to JUST call the original, there is really no reason to provide your version at all. Just make your "generic" array printer not accept char using SFINAE:

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

这篇关于重载输出运营商数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆