Please see the following minimum reproducable example:
#include <iostream>
#include <vector>
#include <algorithm>
// Define inserter operator for std::vector<int>
std::ostream& operator << (std::ostream& os, const std::vector<int>& v) {
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(os, " "));
return os;
}
// Define inserter operator for std::vector<std::vector<int>>
std::ostream& operator << (std::ostream& os, const std::vector<std::vector<int>>& vv) {
// ******* Error in this line *****
std::copy(vv.begin(), vv.end(), std::ostream_iterator<std::vector<int>>(os,"\n"));
// OK. The following works and will call the operator above
for (const std::vector<int>& v : vv) os << v << '\n';
return os;
}
int main() {
std::vector<std::vector<int>> vvi{ {1,2}, {3,4,5}, {6,7,8,9 } };
std::cout << vvi;
return 0;
}
The std::ostream_iterator<std::vector<int>> will not compile, compiler says:
binary '<<': no operator found which takes a right-hand operand of type 'const _Ty' (or there is no acceptable conversion)
Although an inserter operator for std::vector<int> is available.
if I instead use:
for (const std::vector<int>& v : vv) os << v << '\n';
The insert operator for std::vector<int> will be called. But not in the case of the std::ostream_iterator.
CppReference does not help me.
Why does this not compile?