c++ - C++ 使用 ostream_iterator 解决 STL 容器的 ostream 运算符<< 重载
问题描述
我已经为 std::vector 编写了 ostream operator<< 的重载。它基于在这里找到的解决方案,在stackoverflow的深处:
template <typename T, typename AllocT>
std::ostream& operator<< (std::ostream& out, const std::vector<T, AllocT>& v) {
if (!v.empty()) {
out << "[";
std::copy(v.begin(), v.end(), std::ostream_iterator<T>(out, ", "));
out << "\b\b]";
}
return out;
}
对于简单的类型,一切似乎都可以正常工作:
auto vt = std::vector<int>({ 1, 2, 4 });
std::cout << vt;
>> [1, 2, 4]
但是,每当我尝试进行递归时:
auto vt = std::vector<std::vector<int>>({ {1, 2}, {3, 4} });
std::cout << vt;
>> error C2679: binary '<<': no operator found which takes a right-hand operand of type 'const _Ty' (or there is no acceptable conversion)
with
[
_Ty=std::vector<int,std::allocator<int>>
]
... while trying to match the argument list '(std::basic_ostream<char,std::char_traits<char>>, const _Ty)'...
... while compiling class template member function 'std::ostream_iterator<T,char,std::char_traits<char>>
&std::ostream_iterator<T,char,std::char_traits<char>>::operator =(const _Ty &)'
with
[
T=std::vector<int,std::allocator<int>>,
_Ty=std::vector<int,std::allocator<int>>
]
这很奇怪,因为编译器似乎被困在解决重载问题上operator<<(std::basic_ostream<char,std::char_traits<char>>, const std::vector<int,std::allocator<int>>&)
,这(理论上)我们应该能够产生。
据我了解,std::ostream
实际上是一样的std::basic_ostream<char>
,所以这里应该没有任何问题。或者可能是 constness 出了点问题,尽管我也看不出真正的问题。
解决方案
推荐阅读
- javascript - 无法使用快速服务器连接到 socket.io
- python - openCV 中的 Rodrigues 函数不断给出错误“ValueError:matrix must be 2-dimensional”,即使是二维数组
- entity-framework-core - 如何传递 CreateDbContext Args 参数?
- python - 机器人框架捕获关键字标准输出日志
- flutter - 如何防止再次下载图像
- mysql - 什么决定了从物理模式创建表时使用什么约束
- c# - 如何为图像按钮添加选择效果?
- c - 从C中的字符串中提取多个整数
- javascript - ReactChartJS2中的组条形图单击特定元素
- r - While循环嵌套在for循环R中