在运算符重载中使用()

use of () in operator overloading

本文关键字:运算符 重载      更新时间:2023-10-16

我用operator()找到了这段代码。我以前从未见过(我见过+、>、-<<)。有人能解释一下它应该在什么时候使用以及应该如何使用吗?

 class sortResults
    {
    public:
        bool operator() (Result const & a, Result const & b);
    };

这被称为函子(不要与函数编程语言中的函子混淆)。

它模仿一个函数,可以在标准库的函数中使用:

std::vector<Result> collection;
// fill with data
// Sort according to the () operator result
sortResults sort;
std::sort(collection.begin(), collection.end(), sort);

与简单的函数相比,一个很好的优势是它可以保存状态、变量等。你可以用闭包(如果这听起来很像)进行并行

struct GreaterThan{
    int count;
    int value;
    GreaterThan(int val) : value(val), count(0) {}
    void operator()(int val) {
        if(val > value)
            count++;
    }
}
std::vector<int> values;
// fill fill fill
GreaterThan gt(4);
std::for_each(values.begin(), values.end(), gt);
// gt.count now holds how many values in the values vector are greater than 4

这意味着可以调用sortResults实例,就像一个函数需要两个Result参数:

sortResults sr;
Result r1, r2;
bool b = sr(r1, r2);

这样的类被称为"函子"。大多数标准库算法都有重载,它们采用一元或二元函子,比如这个。