bool operator() 有什么作用?

问题描述

我无法理解 GeeksforGeeks 中的这段代码

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Comparison function for sorting the
// set by increasing order of its pair's
// second value
struct comp {
    template <typename T>
  
    // Comparator function
    bool operator()(const T& l,const T& r) const
    {
        if (l.second != r.second) {
            return l.second < r.second;
        }
        return l.first < r.first;
    }
};

我在 StackOverflow 中找到了类似的文章。但它们都没什么不同。

我也想问,写bool operator ()operator bool()有什么区别?

解决方法

bool operator() 为类实例定义运算符 () 并使其接受两个参数进行比较并返回 bool

虽然 operator bool() 定义了 bool 运算符,即使类实例可以转换为 bools


总而言之,第一个函数重载运算符 () 而第二个函数重载运算符 bool


示例

假设你想定义一个比较器并想知道它是否有效,所以你放置了一个标志来知道它,因此你有以下内容。

struct Comparator{
    bool valid{};
    template<class T>
    bool operator()(const T& lhs,const T& rhs)const{
        return lhs<rhs;
    }
    explicit operator bool()const{
        return valid;
    }
};

int main(){
    Comparator x{true};
    std::cout <<((x) ? "x is valid": "x is not valid") << "\n";
    std::cout << "is 1 les than 2: " << std::boolalpha <<  x(1,2);
}

这不是一个好的用例,但我想将两个运算符放在一个类中,以说明它们可以为同一个类定义。

bool 运算符用于可能处于无效状态的对象,例如智能指针和 std::optional<T>,...