Я столкнулся со странной ошибкой при поиске имени в C++.
Ошибку можно воссоздать, используя следующий минимальный пример:
#include <vector>
#include <iostream>
std::ostream& operator<<(std::ostream& out, const std::vector<int>& a) {
for (size_t i = 0; i < a.size(); i++) {
out << a[i] << std::endl;
}
return out;
}
namespace Test {
struct A {
// Label 1
friend std::ostream& operator<<(std::ostream& out, const A&) {
return out << "A" << std::endl;
}
};
struct B {
void printVector() noexcept {
std::vector<int> v{1, 2, 3};
std::cout << v << std::endl; // The error occurs in this line
}
// Label 2
friend std::ostream& operator<<(std::ostream& out, const B&) {
return out << "B" << std::endl;
}
};
}
int main() {
Test::B().printVector();
}
Компиляция приведет к следующему сообщению об ошибке:
cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'
Вы можете сами проверить это здесь: http://cpp.sh/5oya
Странно то, что код компилируется и работает нормально, если вы удалите одну из функций, помеченных // Label 1 соответственно // Label 2.
Теперь мой вопрос: что здесь происходит? Как это можно исправить?
Error: no match for »operator<<« (operand types are »std::ostream {aka std::basic_ostream<char>}« and »std::vector<int>«)- person zuenni   schedule 12.01.2017basic_ostream::operator<<иstd::operator<<. Что странно. Еще более странно: он находит перегрузку, если он помещен в пространство именTest, т. е. он действительно ищет во внешних пространствах имен, а не только в классе и ADL. И это происходит также с онлайн g++ 4.9.2. - person Cheers and hth. - Alf   schedule 12.01.2017