考虑以下代码:
#include <iostream>
namespace ns1
{
struct A
{
};
template <class T>
std::ostream& operator << (std::ostream& os, const T& t)
{
return os << "ns1::print" << std::endl;
}
}
namespace ns2
{
template <class T>
std::ostream& operator << (std::ostream& os, const T& t)
{
return os << "ns2::print" << std::endl;
}
void f (const ns1::A& a)
{
std::cout << a;
}
}
int main()
{
ns1::A a;
ns2::f (a);
return 0;
}
按照标准,编译失败并出现“不明确的重载错误”。
但是为什么? A 的“home”命名空间中的“同样好”的运算符肯定应该优先吗?有什么合乎逻辑的理由不这样做吗?
最佳答案
如果您希望 namespace A
中的重载成为首选,那么您必须向其中添加一些内容以使其实际上更好。比如说,通过使其不是模板:
namespace ns1
{
std::ostream& operator<<(std::ostream&, const A& );
}
否则,如果两者完全等价,那么真的没有概念上的理由来理解为什么一个命名空间中的函数模板比另一个命名空间中的函数模板更受欢迎。毕竟,为什么 A
的命名空间中的函数模板会比 f
的命名空间中的函数模板“更好”? f
的实现者难道不会“知道得更多”吗?仅仅依靠函数签名回避了这个问题。
关于c++ - C++ 重载解析规则中的缺陷?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35634091/