I try to overload the operator<< in a namespace. Additionally, I want to include a debug namespace within the first namespace, where the operator<< does more.
In the main function, I create an object of a class within the first namespace and give it out with std::cout. I expected to have to 'name' the operator before I can do that, as in using test::operator<<, but I don't have to.
This leads to my issue: If I want to use my debug operator now, it is ambiguous and I cannot use it and I don't really understand why.
#include <iostream>
#include <string>
namespace test{
class A{
std::string str_;
public:
explicit A(const std::string& str) : str_{str} {}
inline std::ostream& toStream(std::ostream& os) const {
return os << str_ << "\n";
}
};
std::ostream& operator<< (std::ostream& os, const A& a) {
return a.toStream(os);
}
}
namespace test {
namespace debug {
std::ostream& operator<< (std::ostream& os, const A& a) {
std::string info = "\n\tDebug\n"
"\t\tLine: " + std::to_string(__LINE__) + "\n"
"\t\tFile: " __FILE__ "\n"
"\t\tDate: " __DATE__ "\n"
"\t\tTime: " __TIME__ "\n"
"\t\tVersion: " + std::to_string(__cplusplus) + "\n";
return a.toStream(os) << info;
}
}
}
int main(int argc, const char* argv[]) {
test::A a{"Test"};
if(argc > 1) {
using test::debug::operator<<;
// Ambiguous error
std::cout << a << "\n";
} else {
// Don't need it for some reason
// using test::operator<<;
std::cout << a << "\n";
}
}
using test::operator<<;to tell the compiler where to find the overload, because it is hidden in the namespace "test".__FILE__and__LINE__will always be the file where theoperator<<is defined. I assume you wanted to get the line and file of where you call?