I m 试图利用流输出C阵列。
For array of ints, I wrote the code like this
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;
}
the main function didn t change, However, this time, when I compile it, error occured.
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>]
我如何确定这一点? 感谢你提出任何建议。