我正在尝试使用stl惯用语通过为该对定义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
}
iterator:974:28:对二进制表达式无效的操作数('std :: __ 1 :: ostream_iterator,char,std :: __ 1 :: char_traits> :: ostream_type'(aka'basic_ostream>')和'const std ::: __1 :: pair')
_LIBCPP_INLINE_VISIBILITY ostream_iterator& operator=(const _Tp& __value_)
{
*__out_stream_ << __value_; //// <<<---- Here is the error line
if (__delim_)
*__out_stream_ << __delim_;
return *this;
}
似乎没有找到我的运算符<global命名空间中,而不是在[[std命名空间中?
std::pair<int,int>
不是从全局名称空间输入的,与PC
不同,因此您的operator<<
重载不参与重载解析。如果您在名称空间std
中定义它,则可能会起作用:namespace std {
ostream& operator<<(ostream& o, const P& v) {
return o << "(" << v.first << "," << v.second << ")";
}
}
但是这样做是不正确的,因为pair<int,int>
不依赖于任何用户定义的类型。您最好使用包装器。