c++ - C++ 重载解析规则中的缺陷?

标签 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;
}

按照标准,编译失败并出现“不明确的重载错误”。

但是为什么? 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/

相关文章:

c++ - 停止从标准输入读取

c++ - 访问冲突 - 无法写入位置

C++:如何返回模板类中定义的别名?

c++ - 模板向导的难题

c++ - 在 C++ 中将字符串转换为 LPVOID 和 LPCWSTR

c++ - 将原始像素数据转换为 QPixmap

C++ 对重载函数的奇怪模棱两可的调用

c++ - 命名空间中的变量如何优于全局变量

c++ - 从 C++ 应用程序请求 Windows Vista/7 上的管理员权限

templates - C++/CLI 中的函数模板