std::equal 具有用户定义的函数 class

std::equal function with user-defined class

我正在尝试理解一些示例代码(见下文)。我对 std:equal 函数的理解是,当使用用户定义的类型时,必须定义一个等于 == 运算符以允许该函数执行比较。

所以我不明白这个 int() 运算符(是强制转换吗?)如何执行相同的功能。为什么 equal 函数会尝试将 class A 的实例转换为 int?

#include <set>
#include <iostream>
#include <algorithm>
using namespace std;

struct A
{
   int a;

   A(int a) : a(a) {}
   operator int() const { return a; }  //LINE I
};

int main()
{
    set<A> s{ 3, 9, 0, 2, 1, 4, 5, 6, 6, 9, 8, 2 };
    cout << equal(s.begin(), s.end(), s.begin()) << endl;  //LINE II
}

你可以通过查看这段代码来了解发生了什么:

#include <iostream>


class A {
    public:
        int a;
        A(int a) :    a(a) {}
        //operator int() const {return a;}
};

int main () {

    A a{10};
    A b{20};

    std::cout << std::boolalpha << (a == b) << std::endl; // does not compile
}

如果您对转换运算符进行注释,则代码不会进行比较。如果取消注释,代码会编译,比较是通过将 ab 隐式转换为 int.

来完成的

执行此转换是因为 ints 的标准运算符 == 是评估表达式 a == b 的良好候选者,因此编译器触发隐式转换为 int(感谢@LightnessRacesinOrbit 指出这一点)。