我正在尝试使用 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;
}
而且效果很好。
然后,我将其泛化为更多类型(如字符、 float 等),因此我将原始版本更新如下
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>]
我该如何解决这个问题?感谢您提出任何建议。
最佳答案
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])
关于c++ - 通过ostream输出一个C数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27167495/