【发布时间】:2016-02-25 17:23:09
【问题描述】:
考虑以下代码:
#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'命名空间中的“同样好”的运算符肯定应该优先吗?有什么合乎逻辑的理由不这样做吗?
【问题讨论】:
-
为什么你认为
A的“home”命名空间中的函数应该优先于调用函数f本身的命名空间中的函数?没有办法解决这个模棱两可的问题。错误是唯一明智的做法。 -
因为创建者比命名空间更了解应该如何打印 A?
-
首先,它们是模板。如果创建
A的人想要确保打印A类型的对象的特定行为,他们将提供重载或特化。这将解决这里的歧义。其次,命名空间可以多次打开和关闭,所以A的实现者可能没有提供该功能。
标签: c++ templates namespaces language-lawyer overload-resolution