在下面的代码片段中,我已经重载了
operator==
来比较我的对类型和字符串。但是由于某种原因,编译器没有将我的运算符作为查找函数的匹配项。为什么? 编辑: 感谢所有提出替代方案的建议,但我仍然想了解 为什么。代码看起来应该可以工作;我想知道为什么不行。#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
呢? - sbiclass RegPair: public std::pair<std::string, int> {};
由于你的类现在在全局命名空间中,它将无法找到你版本的operator==。你当前的失败原因是typedef实际上不是typedef,它是类型别名(即类型的另一个名称)。因此,在ADL中它没有帮助。 - Martin Yorkboost::container::flat_map<>
感兴趣,它来自于最近正式接受的Boost.Containers库。我相信该库预计将从1.49开始包含在官方的Boost发行版中。 - ildjarn