ostream_iterator运算符=在pair<int,int>上失败,但在包装器类上工作。我不能为成对<>重载运算符<<吗?
ostream_iterator operator= fails on pair<int,int>, but works on wrapper class. Can't I overload operator<< for pair<>?
我正在尝试使用 stl 习语来打印对向量的内容,方法是为对定义运算符<<,除非我使用包装类,否则它失败了:
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::p air'(
_LIBCPP_INLINE_VISIBILITY ostream_iterator& operator=(const _Tp& __value_)
{
*__out_stream_ << __value_; //// <<<---- Here is the error line
if (__delim_)
*__out_stream_ << __delim_;
return *this;
}
似乎找不到我的运算符<<(ostream&o,const P&(。那是因为它在全局命名空间中而不是在std命名空间中吗?
与PC
不同,std::pair<int,int>
不是来自全局命名空间的类型,因此您的operator<<
重载不参与重载解析。 如果您在命名空间std
中定义它,它可能会起作用:
namespace std {
ostream& operator<<(ostream& o, const P& v) {
return o << "(" << v.first << "," << v.second << ")";
}
}
但是,这样做是不正确的,因为pair<int,int>
不依赖于任何用户定义的类型。您使用包装器是更好的主意。
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- EASTL矢量<向量<int>>连续的
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- C :对矢量进行排序&lt; struct&gt;(结构有2个整数)基于结构的整数之一
- 明确的专业化“ CheckIntmap&lt;&gt;”实例化
- 什么是模板&lt;&gt;inline bla bla
- 编辑C Qlist&lt; object*&gt; gt;QML代码和一些QML警告中的模型
- eigen :: llt&lt;eigen :: matrixxd&gt;具有不完整的类型
- 错误,包括&lt; ctype&gt;在原子上使用C 11
- std::vector<;uint8_t>;当C++11/14启用时,手动复制而不是调用memcpy
- 如何加入向量&lt; int&gt;到C 中的单个INT
- 是std :: set&lt; std :: future&gt;不可能存在
- 是numeric_limits&lt; int&gt; :: is_modulo从逻辑上矛盾
- opencv 2.4.7在iOS错误背景_segm.hpp #include&lt; list&gt;未找到
- 在修改列表后,std :: list&lt; t&gt; :: end()的值是否会更改
- ///<评论></评论>在Visual Studio中