c++ - ostream_iterator operator= 在对上失败,但适用于包装类。我不能为pair<>重载operator<<吗?
问题描述
我正在尝试使用 stl idioms 通过为该对定义 operator<< 来打印对向量的内容,但它失败了,除非我使用包装类:
typedef pair<int, int> P;
// Dump wrapper, just converting implicitly pair<int, int> to PC.
class PC { public: int first; int second; PC(const P& p) { first = p.first; second = p.second;}};
ostream& operator<<(ostream& o, const PC& v) {
return o << "(" << v.first << "," << v.second << ")";
}
ostream& operator<<(ostream& o, const P& v) {
return o << "(" << v.first << "," << v.second << ")";
}
int main(int argc, const char * argv[]) {
P p = {10,20};
cout << p; // works
*ostream_iterator<PC>(cout, ", ") = p; // works
*ostream_iterator<P>(cout, ", ") = p; // fails, error msg below
}
迭代器:974:28:二进制表达式的操作数无效('std::__1::ostream_iterator, char, std::__1::char_traits >::ostream_type'(又名 'basic_ostream >')和 'const std::__1: :一对')
_LIBCPP_INLINE_VISIBILITY ostream_iterator& operator=(const _Tp& __value_)
{
*__out_stream_ << __value_; //// <<<---- Here is the error line
if (__delim_)
*__out_stream_ << __delim_;
return *this;
}
似乎没有找到 my operator<<(ostream&o, const P&) 。那是因为它在全局命名空间中而不是在std命名空间中吗?
解决方案
std::pair<int,int>
不同于全局命名空间中的is 类型PC
,因此您的
operator<<
重载不参与重载解析。如果您在命名空间中定义它,它可能会起作用std
:
namespace std {
ostream& operator<<(ostream& o, const P& v) {
return o << "(" << v.first << "," << v.second << ")";
}
}
但是这样做是不正确的,因为pair<int,int>
它不依赖于任何用户定义的类型。您使用包装器是更好的主意。
推荐阅读
- python - PyQt5:当通过来自另一个线程的信号发送像素图时,Python 会因 SIGSEGV *有时* 而崩溃
- r - 在 R 中的多个列上重复组分析
- jquery - 针对 AWS 预签名 URL 的 PUT 请求的 SignatureDoesNotMatch
- file - 无法将任何文件上传到谷歌云存储
- c# - 音频不会在特定场景中停止播放
- utf-8 - 如何在 Rust 中获取 char 的 UTF-8 索引
- adobe-xd - Adobe Xd:Windows 10 上的 iOS UI 工具包 - 后退图标、选项卡按钮、其他导航按钮不可见
- php - 无法将具有特征的父组件中的选定数据数组传递给嵌套组件
- azure - Azure Functions - 并行/并发函数执行和横向扩展
- python - sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL 约束失败