cpp*_*lex 8 c++ templates namespaces language-lawyer overload-resolution
请考虑以下代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
根据标准,编译失败并出现"模糊过载错误".
但为什么?当然,A''home'命名空间中"同样好"的运算符应该优先?有没有合理的理由不这样做?
Bar*_*rry 10
如果你想要重载namespace A比你需要添加一些东西,以使它实际上更好.说,使它不是一个模板:
namespace ns1
{
std::ostream& operator<<(std::ostream&, const A& );
}
Run Code Online (Sandbox Code Playgroud)
否则,实际上没有概念上的理由可以看出为什么一个命名空间中的函数模板优先于另一个命名空间中的函数模板,如果两者完全等效的话.毕竟,为什么A命名空间中的函数模板比命名空间中的函数模板"更好" f?f"知道更好" 的实施者不会吗?完全依靠功能签名来回避这个问题.
| 归档时间: |
|
| 查看次数: |
176 次 |
| 最近记录: |