std::greater<int>()(100, 300),为什么它有效?
std::greater<int>()(100, 300), why is it working?
根据我的理解,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_to
。std::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)
中,您缺少一对括号。
相关文章:
- 为什么是0;C++中的有效语句
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 为什么这种直接初始化有效?(C++17)
- 为什么在引用指针时将 const 放在 & 符号的左侧有效,而在右侧则无效?
- 为什么浮点数的矢量化比双精度更有效?
- 为什么模板参数中的双冒号有效?
- 为什么在这种情况下递增阵列名称有效?
- 为什么TinyXML2的XMLDocument::FirstChild()函数在尝试解析这个有效的XML文件时返回NULL?
- 这是什么代码?为什么它有效?C++
- 为什么别名声明不是有效的 init 语句(/simple-declaration)?
- 为什么在 C/C++ 中交织 switch/for/if 语句是有效的?
- 为什么这个复合语句作为用大括号和括号括起来的语句序列似乎不是有效的语句表达式
- 为什么使用不匹配的参数调用重载函数仍然有效
- 通过指针调用模板类成员函数 [为什么这是有效的 c++]?
- 将第一个派生类转换为第二个派生类 - 为什么有效?
- 通过 typedef 模板<类型名 T、T> 强制模板实例化 - 为什么有效?
- 这究竟为什么有效?(静态还是其他?)
- 从 r 值引用转换为 l 值引用,为什么有效
- 默认模板参数 - 不必来自右边?为什么有效?
- 为什么 X 有效但未声明?C++