数组的重载输出运算符
Overloading output operator for arrays
根据这个答案,对 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 << "]";
语句。
正确的方法是什么?
问题是打印字符数组的operator<<
的标准重载是这样的:
template< class CharT, class Traits >
basic_ostream<CharT,Traits>& operator<<( basic_ostream<CharT,Traits>& os,
const char* s );
因此,当您提供您的:
template <size_t arrSize>
std::ostream& operator<<( std::ostream& out, const char( &arr )[arrSize] )
这将是模棱两可的:我们有两个不同的函数模板,具有相同的转换序列,其中任何一个都不比另一个更专业。
但是,由于您希望您的版本仅调用原始版本,因此根本没有理由提供您的版本。只需使用 SFINAE 使您的"通用"阵列打印机不接受char
:
// Print an array
template<typename T1, size_t arrSize,
typename = std::enable_if_t<!std::is_same<T1,char>::value>>
std::ostream& operator <<( std::ostream& out, const T1( & arr )[arrSize] )
{ /* rest as before */ }
相关文章:
- 尝试重载输出运算符时,我无法遍历对象向量
- 字符串数组上的 sizeof 运算符以 C++ 为单位给出不同的输出
- 如何为流输出运算符提供重载<<模板'using'类型别名?
- 在C++中重载输入/输出运算符
- 重载 ostream << 运算符,指针作为参数,导致输出上的内存地址
- 如何调用继承的重载运算符<<并在派生类的输出中添加更多文本?
- 为什么带有逻辑和运算符以及增量运算符的 c++ 程序给出的输出与预期不同?
- 如何处理自定义输出运算符中的 iomanips?
- 使输出流式处理运算符适用于 boost::variant<std::vector<int>、int、double 的正确方法是什么>
- C 和 C++ 中运算符大小的不同输出
- 是否可以转换 c++ 运算符新输出?
- C++ - <<运算符重载,链表 - 地址而不是标准输出
- 如何输入和输出方括号运算符 []
- C++ 输出流运算符 <<() 中的字符何时加宽?
- 我使用箭头运算符打印出对象的变量值,并得到一些随机值作为输出
- 编译器将输出的流运算符<<解释为用于按位左移的二进制运算符<<
- 使用模板化运算符输出集合集合<<
- 重载运算符<<输出布尔值.为什么
- C++重载运算符<<输出地址
- 如何重载运算符<<输出模板内定义的向量?