【发布时间】:2021-03-16 05:51:04
【问题描述】:
在下面的 sn-p 代码中,我重载了 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::map? -
@sbi:这是一个简单的例子,基于在更大的代码库中找到的东西。还有其他一些约束可以使用想要使用对的向量。
-
@dave:我知道这样做是有原因的(事实上,我过去也这样做过),但考虑到我们有时会遇到的问题类型,我认为这是最好的至少问问。
-
而不是 typedef 创建你自己的类:
class RegPair: public std::pair<std::string, int> {};因为你的类现在在全局命名空间中,它不会找到你的 operator== 版本。您当前失败的原因是 typedef 并不是真正的 typedef 它是类型别名(即类型的另一个名称)。因此它对 ADL 没有帮助。 -
@dave, @sbi :您可能对最近正式接受的Boost.Containers 库中的
boost::container::flat_map<>感兴趣。我相信该库有望从 1.49 开始包含在官方 Boost 发行版中。