【问题标题】:ostream_iterator operator= fails on pair<int,int>, but works on wrapper class. Can't I overload operator<< for pair<>?ostream_iterator operator= 在 pair<int,int> 上失败,但适用于包装类。我不能为pair<>重载operator<<吗?
【发布时间】:2020-03-20 06:08:38
【问题描述】:

我正在尝试使用 stl idioms 通过为该对定义运算符

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;
    }

似乎没有找到 my operatorglobal 命名空间中,而不是在 std 命名空间中吗?

【问题讨论】:

    标签: c++ templates stl iterator ostream


    【解决方案1】:

    std::pair&lt;int,int&gt; 不是来自全局命名空间的类型,这与 PC 不同,所以你的 operator&lt;&lt; 重载不参与重载决议。 如果您在命名空间std 中定义它,它可能会起作用:

    namespace std {
        ostream& operator<<(ostream& o, const P& v) {
            return o << "(" << v.first << "," << v.second << ")";
        }  
    }
    

    但是这样做是不正确的,因为pair&lt;int,int&gt; 不依赖于任何用户定义的类型。您使用包装器是更好的主意。

    【讨论】:

    • 除非另有说明,将该函数添加到std 是无效的。
    猜你喜欢
    • 1970-01-01
    • 2020-10-22
    • 2021-11-18
    • 1970-01-01
    • 2015-08-18
    • 1970-01-01
    • 1970-01-01
    • 2019-02-20
    相关资源
    最近更新 更多