通过 ostream 输出 C 数组

Output a C array through ostream

本文关键字:数组 输出 ostream 通过      更新时间:2023-10-16

我正在尝试使用 iostream 输出 C 数组。

对于整数数组,我像这样编写代码

template <size_t N>
ostream& operator<< (ostream& os, const int (&x)[N])
{
    for(int i=0; i<N; i++)
        os<<x[i]<<",";
    return os;
}
int main()
{
    int arr[]={1,2,3};
    cout<<arr<<endl;
    return 0;
}

而且效果很好。

然后,我会将其推广到更多类型(如字符、浮点数等),因此我更新原始版本

如下
template <class T, size_t N>
ostream& operator<< (ostream& os, const T (&x)[N])
{
    for(int i=0; i<N; i++)
        os<<x[i]<<",";
    return os;
}

主函数没有改变,但是,这次,当我编译它时,发生了错误。

In function `std::ostream& operator<<(std::ostream&, const T (&)[N]) [with T = int, long unsigned int N = 3ul]':
a.cpp:15:   instantiated from here
a.cpp:9: error: ambiguous overload for `operator<<' in `(+os)->std::basic_ostream<_CharT, _Traits>::operator<< [with _CharT = char, _Traits = std::char_traits<char>]((*((+(((long unsigned int)i) * 4ul)) + ((const int*)x)))) << ","'
/usr/lib/gcc/x86_64-redhat-linux/3.4.5/../../../../include/c++/3.4.5/bits/ostream.tcc:121: note: candidates are: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long int) [with _CharT = char, _Traits = std::char_traits<char>] <near match>
/usr/lib/gcc/x86_64-redhat-linux/3.4.5/../../../../include/c++/3.4.5/bits/ostream.tcc:155: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long unsigned int) [with _CharT = char, _Traits = std::char_traits<char>] <near match>
/usr/lib/gcc/x86_64-redhat-linux/3.4.5/../../../../include/c++/3.4.5/bits/ostream.tcc:98: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(bool) [with _CharT = char, _Traits = std::char_traits<char>]

我该如何解决这个问题?谢谢你的任何建议。

operator << (const char*) 已经存在与您的模板不明确的重载。

您可以使用 SFINAE 限制您的模板以排除char

template <class T, size_t N,
     typename = typename std::enable_if<!std::is_same<char, T>::value>::type>
ostream& operator<< (ostream& os, const T (&x)[N])

编译器实际上是在抱怨","。如果将其删除,您将看到它工作正常。

template <class T, size_t N>
ostream& operator<< (ostream& os, const T (&x)[N])
{
    for(size_t i = 0; i < N; i++)
        os << x[i];
    return os;
}
// Output: 123

字符串文本的类型是一个N常量字符的数组,但它衰减为const char*,在os << x[i] << ","调用中产生歧义。