【发布时间】:2019-07-16 16:18:55
【问题描述】:
编译以下代码失败,因为第二个函数找不到第一个函数,即使它位于命名空间之外。我自己无法弄清楚问题所在,到目前为止我还没有在网上找到任何答案。
test.cpp:
#include <bits/stdc++.h>
struct myclass {};
template <typename T, typename U>
std::ostream& operator<< (std::ostream &os, const std::pair<T, U> &p) {
os << "(" << p.first << ", " << p.second << ")";
return os;
}
namespace my {
void operator<< (std::ostream os, myclass m) {
std::cout << std::pair<int, int>(5, 4); // This is line 13.
}
}
int main() {
return 0;
}
编译器给出的错误 (g++ test.cpp -O2 -o test.exe):test.cpp:13:13: error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'std::pair<int, int>').
它继续,给出了一长串关于operator<<可能意味着什么的建议。
观察1:如果两个函数名称不同,不会出错。
观察2:如果namespace my {去掉},不会出错发生。
【问题讨论】:
-
通过显式调用全局运算符:
::operator<<(std::cout, std::pair<int, int>(5, 4));它应该可以工作,但这非常丑陋(并且不可链接)。如果有更好的方法,我不会将其发布为答案。 -
更好的方法是在调用前使用 using 指令 (
using ::operator<<;)。至于为什么查找最终没有在全局命名空间中找到候选人......
标签: c++ operator-overloading overloading name-lookup