std::istream_iterator doesn't work with std::pair

48 Views Asked by At

Simple example. This code doesn't compile:

#include <iostream>
#include <iterator>

using test_t = std::pair<int, int>;

std::istream& operator>>(std::istream& in, test_t& t) {
    return in >> t.first >> t.second;
}

int main() {
    auto it = std::istream_iterator<test_t>(std::cin);
}

compilation log contains bunch of subsitution errors and starts with

/usr/include/c++/8.2.1/bits/stream_iterator.h:121:17: error: no match for 'operator>>' (operand types are 'std::istream_iterator<std::pair<int, int> >::istream_type' {aka 'std::basic_istream<char>'} and 'std::pair<int, int>')
      *_M_stream >> _M_value;

But if i change test_t to struct like this:

#include <iostream>
#include <iterator>

struct test_t {
    int first;
    int second;
};

std::istream& operator>>(std::istream& in, test_t& t) {
    return in >> t.first >> t.second;
}

int main() {
    auto it = std::istream_iterator<test_t>(std::cin);
}

it compiles fine. Or if i keep std::pair, but call operator>> directly from std::cin, it works fine too:

#include <iostream>
#include <iterator>

using test_t = std::pair<int, int>;

std::istream& operator>>(std::istream& in, test_t& t) {
    return in >> t.first >> t.second;
}

int main() {
    test_t t;
    std::cin >> t;
}

Does anyone know why does it happen? Or it just a bug in compiler or something?

btw, compiler is g++ (GCC) 8.2.1

0

There are 0 best solutions below