"No match operator==" 使用 std::equal 和命名空间时出错

"No match operator==" error when using std::equal and namespace

使用 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== 移动到定义了 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