gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:42:59 25 4
gpt4 key购买 nike

在以下代码片段中,我重载了 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com