使用 ostream_iterator 重载类型别名和 operator<< 导致操作数无效

EJT*_*EJT 1 c++ iterator c++11

我试图理解为什么我可以在以下代码中使用 ostream_iterator forEdge1但不能使用 for Edge

#include <fstream>
#include <iostream>                  // for std::cout
#include <utility>                   // for std::pair

using VertexName = uint32_t;
using Edge = std::pair<VertexName, VertexName>;

struct Edge1 : public Edge {
    Edge1(VertexName x, VertexName y) : Edge(x,y) {};
};

std::ostream&
operator<<(std::ostream& os, const Edge& e) {
    os << "(" << e.first << ", " << e.second << ")";
    return os;
}

int main(int,char*[])
{
    auto e1 = Edge(4,5);
    auto e2 = Edge1(5,6);
    std::cout << e1 << ", " << e2 << std::endl;
    auto it = std::ostream_iterator<Edge1>(std::cout, ", ");
    //*it++ = e1;
    *it++ = e2;
}
Run Code Online (Sandbox Code Playgroud)

``

虽然我可以打印出两者e1e2使用重载operator<<(std::stream& os, const Edge& e)函数,但如果我尝试将 ostream_iterator 更改为std::stream_iterator<Edge>(std::cout, ", ")并取消注释该*it++ = e1行,则会从 clang-5.0 中收到以下错误。

error: invalid operands to binary expression ('ostream_type' (aka 'basic_ostream<char, std::__1::char_traits<char> >') and 'const std::__1::pair<unsigned int, unsigned int>')
            *__out_stream_ << __value_;
            ~~~~~~~~~~~~~~ ^  ~~~~~~~~
/main.cpp:25:11: note: in instantiation of member function 'std::__1::ostream_iterator<std::__1::pair<unsigned int, unsigned int>, char, std::__1::char_traits<char> >::operator=' requested here
    *it++ = e1;
Run Code Online (Sandbox Code Playgroud)

Ric*_*ges 6

Edge不是类型,它是std::pair.

当然,ADL 没有找到operator<<for的重载,Edge因为它定义在错误的命名空间中……并且您不允许在 std 命名空间中注入重载。

解决方法是:

#include <fstream>
#include <iostream>                  // for std::cout
#include <utility>                   // for std::pair
#include <iterator>                   // for std::ostream_iterator

using VertexName = uint32_t;

// Edge is now a type, in the global namespace...
struct Edge : std::pair<VertexName, VertexName> {
    using std::pair<VertexName, VertexName>::pair;
};

struct Edge1 : public Edge {
    Edge1(VertexName x, VertexName y) : Edge(x,y) {};
};

// ...and this operator<< is defined in the global namespace so
// ADL will now find it.
std::ostream&
operator<<(std::ostream& os, const Edge& e) {
    os << "(" << e.first << ", " << e.second << ")";
    return os;
}

int main(int,char*[])
{
    auto e1 = Edge(4,5);
    auto e2 = Edge1(5,6);
    std::cout << e1 << ", " << e2 << std::endl;
    auto it = std::ostream_iterator<Edge>(std::cout, ", ");
    *it++ = e1;
    *it++ = e2;
}
Run Code Online (Sandbox Code Playgroud)