通过 ostream 输出 C 数组
Output a C array through ostream
我正在尝试使用 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] << ","
调用中产生歧义。
相关文章:
- 将值从二维数组输出到文本文件
- 为什么我的数组输出一个不在其中的元素
- 长度为 20 的 Cout'ing 数组输出 23 个字符
- 将矢量数组输出到 tex 文件中,错误
- 来自不同位置的数组输出的执行时间
- 数组输出中缺少字符
- 字符数组输出 - C++
- C 合并的数组输出错误
- 制作垫子类型对象的数组.输出窗口显示同一帧
- C++数组输出地址
- 字符数组输出正确,但实际上没有存储正确的值
- 字符串数组输出
- 为什么在将字符数组输出到控制台时会得到垃圾值
- 字符数组输出额外的字符
- 从字符数组输出到控制台
- 为什么计数从字符数组输出错误的字符
- 动态初始化的 2D 数组输出错误
- C++指针和2d数组输出
- c++中奇怪的char数组输出
- 类函数中的c++字符数组输出