c++ - find() 使用重载运算符==

标签 c++ operator-overloading overload-resolution argument-dependent-lookup name-lookup

我尝试使用重载运算符 ==() 在 vector 中查找元素。但是,如果在以下代码中使用 type1,则输出为 1 和 0(未找到)。使用type2同时给出1和1。环境是Xubuntu 12.04和g++版本4.6.3。

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

typedef pair<string, int> type1;
struct type2: public type1 {};
#define TYPE type1

bool operator== (const TYPE& lhs, const TYPE& rhs) {
    return lhs.first == rhs.first;
}

int main()
{
    vector<TYPE> vec;
    TYPE v1, v2;

    v1.first = "abc"; v1.second = 1; vec.push_back(v1);
    v2.first = "abc"; v2.second = 2;

    cout << (v1 == v2) << endl;
    cout << (find(vec.begin(), vec.end(), v2) != vec.end()) << endl;
}

最佳答案

std::pair有默认值 operator==在命名空间 std ,这是任意对的模板,比较 firstsecond领域。该运算符在四种情况之一中被选中,即 findTYPE == type1 .虽然细节有点复杂:

TYPE == type1 实际发生了什么是(如果我错了请纠正我)

  • v1 == v2 ADL(参数相关名称查找)用于查找 operator==std ,意味着这个运算符被添加到正常的重载集中。但是,当前翻译单元中的非模板版本仍然优先于模板 operator==来自 std .
  • std::find调用在 std 中实例化,因此查找 operator==直接在std开始.它会找到一个匹配项(不使用 ADL!),因此不会搜索本应包含 OP 自己的运算符的封闭范围。

对于 TYPE == type2

  • v1 == v2很简单 - 它直接找到 operator==在封闭的命名空间中。
  • std::find也在 std 中实例化,但是来自主作用域的自定义运算符被添加到使用 ADL 的重载决议集,然后发现它比 std 中的更具体.

关于c++ - find() 使用重载运算符==,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19187766/

相关文章:

c++ - 重载调用不明确

c++ - 将 n 个 char* 复制到另一个里面

c++ - 使用 DHCP 获取 IP 地址、网关、掩码和广播信息

C++ 自定义列表迭代器错误

c++ - 没有参数特征名称的重载括号运算符

C++ istream 运算符重载 - 即使声明为 friend 也无法访问数据成员

c++ - 隐式转换为 std::string

c++ - 在析构函数之前省略关键字 virtual 仍然有效

c++ - 编译器可以告诉我它选择了哪个重载函数或模板函数吗?

c++ - 如何指定可调用对象应指向的重载?