c++ - 使用 std::equal 和命名空间时出现 "No match operator=="错误

标签 c++ namespaces

使用 std::equal 时出现编译错误(“不匹配运算符==”)并且我的类在单独的命名空间中定义(定义了适当的运算符)。
这是我使用 std::equal 的工作示例但没有命名空间,还有 没有编译错误

#include <vector>
#include <algorithm>

struct K {
    int a;
};

struct V {
    int b;
};


inline bool operator== (const K& lhs, const V& rhs) {
    return lhs.a == rhs.b;
}

inline bool operator== (
const std::vector<K>& lhs, const std::vector<V>& rhs) {
    return std::equal(lhs.begin(), lhs.end(), rhs.begin());
}
但是当我为我的类使用命名空间时,有“无匹配运算符”错误
#include <vector>
#include <algorithm>


namespace nk {
  struct K {
    int a;
};  
}

namespace nv {
  struct V {
    int b;
};  
}

inline bool operator== (const nk::K& lhs, const nv::V& rhs) {
    return lhs.a == rhs.b;
}

inline bool operator== (const std::vector<nk::K>& lhs, const std::vector<nv::V>& rhs) {
    return std::equal(lhs.begin(), lhs.end(), rhs.begin());
}

/opt/compiler-explorer/gcc-10.2.0/include/c++/10.2.0/bits/stl_algobase.h:1107:22: error: no match for 'operator==' (operand types are 'const nk::K' and 'const nv::V')


还有没有错误std::equal替换为简单循环(比较运算符在这种情况下效果很好):
inline bool operator== (const std::vector<nk::K>& lhs, const std::vector<nv::V>& rhs) {
    if (lhs.size() != rhs.size()) {
        return false;
    }

    for(std::size_t i=0; i<lhs.size(); i++) {
        if (!(lhs[i]==rhs[i])) {
            return false;
        }
    }
    return true;
}
代码已使用 Compiler Explorer 和 GCC 10.0.2 进行测试(我还测试了其他 GCC 版本)

最佳答案

问题是图书馆喜欢 std::equal找不到 operator==在全局范围内定义。
您可以移动operator==进入命名空间 where KV定义为验证 ADL . (PS 你的第一个代码片段也因为 ADL 起作用。)
例如。

namespace nk {
  struct K {
    int a;
  };  
}

namespace nv {
  struct V {
    int b;
  };  

  inline bool operator== (const nk::K& lhs, const nv::V& rhs) {
      return lhs.a == rhs.b;
  }
}
LIVE

关于c++ - 使用 std::equal 和命名空间时出现 "No match operator=="错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66999617/

相关文章:

c++ - .cpp 文件中定义的 Constexpr 构造函数导致链接错误

c++ - 递归函数扫描字符串添加ASCII

c# - 验证 VAB 配置文件中的程序集和命名空间

php - 在函数内部使用 php 命名空间

visual-studio-2010 - 安装了来自 NuGet 的引用,但 VS2010 找不到命名空间

c++ - 为什么以这种方式使用 move 语义无效?

c++ 和 mongodb - 无法编译 - 对`boost::system::generic_category() 的 undefined reference

c++ - 计算 'atmost K' 和 'atmost K-1' 的值以获得 'equals K' 的答案背后的直觉

python - 考虑三个嵌套函数。最内层的函数可以访问最外层的命名空间吗?

xslt - 如何避免 XSLT 中所有子节点的命名空间声明