I have the following code:
#include <iostream>
#include <vector>
namespace X {
std::ostream& operator<<(std::ostream& os,const std::vector<double>& v){
for (int i=0;i<v.size();i++){os << v[i] << " ";}
return os;
}
namespace Y {
struct A {std::vector<double> x;};
std::ostream& operator<<(std::ostream& os,const A& a){
os << a.x << std::endl;
return os;
}
}
}
using namespace X;
int main(int argc, char** argv) {
std::vector<double> v(10,0);
std::cout << v << std::endl;
Y::A a;
std::cout << a << std::endl;
return 0;
}
The first overload works, but the second one does not. For some reason it cannot find the first one. I get the error:
no match for 'operator<<' (operand types are 'std::ostream
{aka std::basic_ostream<char>}' and 'const std::vector<double>')
os << a.x << std::endl;
^
I do not understand why I get this error. For example something like this seems to be completely valid:
namespace A {
void foo(){}
namespace B {
void bar(){foo();}
}
}
However, the only way to fix the above problem was to put the second overload also in X. Why is it not possible to have it in the same namespace as the struct (ie. X::Y)?
PS: I was reading on ADL and I found some related questions (e.g. this and this, but what I understood from reading this, the above should work.
using X::operator<<
in namespaceY
. – OsteoblastX
. Still it would be nice to know why ADL does not apply in this case. – Ropable