为什么不使用我的operator ==的std :: find()? [英] Why isn't std::find() using my operator==?

查看:43
本文介绍了为什么不使用我的operator ==的std :: find()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In the following snippet of code, I've overloaded the operator== to compare my pair type with string. But for some reason, the compiler isn't finding my operator as a match for the find function. Why not?

感谢您提出的所有替代建议,但我仍然想了解为什么.该代码看起来应该可以工作.我想知道为什么没有.

Thanks for all the suggestions for alternatives, but I'd still like to understand why. The code looks like it should work; I'd like to know why it doesn't.

#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 == 来使用.

The problem is that std::find is a function template and it uses argument-dependent lookup (ADL) to find the right operator== to use.

这两个参数都在 std 命名空间中( std :: pair< std :: string,int> std :: string ),因此ADL首先在 std 命名空间中查找.在那里找到了一些 operator == (哪一个都没关系;标准库中有很多东西,如果您已经包含了< string> ,则位于至少可以找到将两个 std :: basic_string< T> 对象进行比较的对象.

Both of the arguments are in the std namespace (std::pair<std::string, int> and std::string), so ADL starts by looking in the std namespace. There it finds some operator== (which one, it doesn't matter; there are lots in the Standard Library and if you've included <string>, at least the one that compares two std::basic_string<T> objects could be found).

由于在 std 名称空间中发现了 operator == 重载,因此ADL停止搜索封闭范围.找不到位于全局命名空间中的重载.名称查找发生在重载解析之前;在名称查找过程中,参数是否匹配无关紧要.

Because an operator== overload is found in the std namespace, ADL stops searching enclosing scopes. Your overload, which is located in the global namespace, is never found. Name lookup occurs before overload resolution; it doesn't matter during name lookup whether the arguments match.

这篇关于为什么不使用我的operator ==的std :: find()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆