【发布时间】:2015-09-17 01:41:11
【问题描述】:
根据this answer,C风格数组重载输出操作符<<的正确方法是这样的——:
#include <iostream>
using namespace std;
template <size_t arrSize>
std::ostream& operator<<( std::ostream& out, const char( &arr )[arrSize] )
{
return out << static_cast<const char*>( arr ); // use the original version
}
// Print an array
template<typename T1, size_t arrSize>
std::ostream& operator <<( std::ostream& out, const T1( & arr )[arrSize] )
{
out << "[";
if ( arrSize )
{
const char* separator = "";
for ( const auto& element : arr )
{
out << separator;
out << element;
separator = ", ";
}
}
out << "]";
return out;
}
int main()
{
int arr[] = {1, 2, 3};
cout << arr;
}
但我仍然收到编译器错误
error: ambiguous overload for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'const char [2]')
对于out << "["; 和out << "]"; 语句。
这样做的正确方法是什么?
【问题讨论】:
标签: c++ arrays templates pretty-print