c++ - 为什么 std::find() 不使用我的 operator==?

标签 c++ stl

在以下代码片段中,我重载了 operator== 以将我的配对类型与字符串进行比较。但由于某种原因,编译器没有找到我的运算符作为 find 函数的匹配项。为什么不呢?

编辑:感谢您对替代方案的所有建议,但我仍然想了解为什么。代码看起来应该可以工作;我想知道为什么没有。

#include <vector>
#include <utility>
#include <string>
#include <algorithm>

typedef std::pair<std::string, int> RegPair;
typedef std::vector<RegPair> RegPairSeq;

bool operator== (const RegPair& lhs, const std::string& rhs)
{
    return lhs.first == rhs;
}

int main()
{
    RegPairSeq sequence;
    std::string foo("foo");
    // stuff that's not important
    std::find(sequence.begin(), sequence.end(), foo);
    // g++: error: no match for 'operator==' in '__first. __gnu_cxx::__normal_iterator<_Iterator, _Container>::operator* [with _Iterator = std::pair<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int>*, _Container = std::vector<std::pair<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int>, std::allocator<std::pair<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int> > >]() == __val'
    // clang++: error: invalid operands to binary expression ('std::pair<std::basic_string<char>, int>' and 'std::basic_string<char> const')
}

最佳答案

问题是std::find是一个函数模板,它使用参数相关查找 (ADL) 来查找正确的 operator==使用。

两个参数都在 std 中命名空间( std::pair<std::string, int>std::string ),因此 ADL 首先查看 std命名空间。它在那里找到一些 operator== (哪一个没关系;标准库中有很多,如果你包含了 <string> ,至少可以找到比较两个 std::basic_string<T> 对象的那个)。

因为 operator==std 中发现过载命名空间,ADL 停止搜索封闭范围。永远找不到位于全局命名空间中的重载。名称查找发生在重载解析之前;在名称查找期间参数是否匹配并不重要。

关于c++ - 为什么 std::find() 不使用我的 operator==?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7287224/

相关文章:

c++ - SIMD 内在和持久变量/状态

C++ std::map 运行超出范围

c++ - Boost 二进制文件读取错误 unsupported version

c++ - 是否可以在单个通用引用方法中实现 std::vector 的两个 Push_back(..) 方法?

STL - STL count_if 的标准谓词

C++14/1y : Standard ref for "operator+ must take either one or two arguments"?

c++ - 绘制 sf::Text 时出现问题。 C++

c++ - Range-for 循环识别错误类型 (C2440)

c++ - 如何遍历类指针的 vector

c++ - 是否有任何好的 C++ 自定义分配器可以最大化引用的位置?