std::greater<int>()(100, 300),为什么它有效?

std::greater<int>()(100, 300), why is it working?

本文关键字:为什么 有效 int gt std greater lt      更新时间:2023-10-16

根据我的理解,Functor应该这样使用

std::greater<int> g;
std::cout << std::boolalpha << g(10, 3) << std::endl; 

或作为函数的参数。

find_if(v.begin(), v.end(), std::greater<int>())

但是这是什么意思?

std::cout << std::greater<int>()(100, 300) << std::endl; // output: false

当我像下面这样使用not_equal_to时,它不能传递compile:

int* pt = std::adjacent_find (numbers, numbers+5, std::not_equal_to<int>(1,1)) +1;

为什么它工作?

在第一个代码中,你在函子上调用operator(),并输出结果。

std::cout << std::greater<int>()(100, 300) << std::endl; // output: false  
             ~~~~~~~~~~~~~~~~~~~ <- create a temporary object(functor)
                                ~~~~~~~~~~ <- call operator() on the temporary object

为什么不工作?

在第二段代码中,你将函子传递给一个算法,并且该函子将在算法内部通过调用operator()来调用。

int* pt = std::adjacent_find (numbers, numbers+5, std::not_equal_to<int>(1,1)) +1;
                                                  ~~~~~~~~~~~~~~~~~~~~~~~~~~~

您正在尝试通过一个具有2个参数的actor创建临时std::not_equal_tostd::not_equal_to没有这个actor,所以只需将其更改为使用默认的actor,就像您使用std::greater调用std::find_if一样。

int* pt = std::adjacent_find (numbers, numbers+5, std::not_equal_to<int>()) +1;

如您所知,对于具有无参数构造函数的类X,您可以将X()作为其他表达式的一部分来创建(临时堆栈-)对象。Ie。以下两个代码是相同的[如果callFunc不期望可变引用等]:

X x;  
callFunc(x);  
callFunc(X());

现在std::greater<int>()(100, 300)像上面一样创建了一个std::greater<int>的对象,并执行带形参100和300的函子。它只是前两个代码示例的组合,一对圆括号用于创建对象,另一个用于调用对象。在std::not_equal_to<int>(1,1)中,您缺少一对括号。