【问题标题】:Output a C array through ostream通过ostream输出一个C数组
【发布时间】:2014-11-27 09:47:02
【问题描述】:

我正在尝试使用 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;
}

main函数没变,但是这次编译的时候出错了。

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

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

【问题讨论】:

    标签: c++ arrays iostream


    【解决方案1】:

    operator &lt;&lt; (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])
    

    【讨论】:

    • 嗨,@Jarod42,即使已经存在 operator
    • std::ostreamstd::basic_stream&lt;char&gt;,所以不同模板函数之间存在歧义。
    • @Jarod42 实际上...如果有两个有效的模板特化,则选择最特化的。如果不检查标准,我希望 const T (&amp;x)[N] 更专业(虽然我不确定),而且对于第一个参数来说显然更专业。
    【解决方案2】:

    编译器实际上是在抱怨","。如果你删除它,你会发现它工作正常。

    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 的数组,但它会衰减为const char*,从而在os &lt;&lt; x[i] &lt;&lt; "," 调用中产生歧义。

    【讨论】:

      猜你喜欢
      • 2019-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-06
      • 1970-01-01
      • 1970-01-01
      • 2020-08-09
      • 1970-01-01
      相关资源
      最近更新 更多