【发布时间】:2018-06-12 07:53:36
【问题描述】:
我想将一些私有库class ns::A 输出到plog,所以我将operator << 重载添加到ns::A。
以下代码无法编译。
error: no match for ‘operator<<’ (operand types are ‘std::ostringstream’ {aka ‘std::__cxx11::basic_ostringstream<char>’} and ‘const ns::A’)
out << t;
~~~~^~~~
但是将命名空间other 更改为ns、plog、plog::detail 或std 可以使编译错误消失,为什么?
std::cout<< 和 std::ostringstream<< 无论如何都可以正常工作。
#include <iostream>
#include <sstream>
namespace plog {
namespace detail {}
struct Record {
template <typename T>
Record& operator<<(const T& t) {
using namespace plog::detail;
out << t;
return *this;
}
std::ostringstream out;
};
}
namespace ns {
struct A {};
}
namespace other {}
namespace other { // changing other to ns, plog, plog::detail or std will fix compiling error
inline std::ostream& operator<<(std::ostream& os, const ns::A& a) { return os; }
}
int main() {
ns::A a;
using namespace plog;
using namespace plog::detail;
using namespace ns;
using namespace other;
std::cout << a;
std::ostringstream oss;
oss << a;
plog::Record s;
s << a; // compiling error
}
【问题讨论】:
-
错误是什么?
-
This name lookup reference 可能会有所帮助。尤其是关于argument-dependent lookup的部分。
-
错误:'operator'} 和 'const ns::A ') 出
-
using namespace other;适用于main范围,不适用于 Record& 运算符
标签: c++ operator-overloading overloading name-lookup