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

标签 c++ functor

根据我的理解,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 时,它无法通过编译:

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

最佳答案

Why is it working?

在第一个代码中,您在仿函数上调用operator(),并打印出结果。

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

Why isn't it working?

在第二段代码中,您将仿函数传递给算法,并且将通过在其上调用 operator() 来在算法内部调用仿函数。

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

您正在尝试通过采用 2 个参数的构造函数创建临时 std::not_equal_tostd::not_equal_to 没有该 ctor,因此只需将其更改为使用默认 ctor,就像使用 std 调用 std::find_if 所做的那样: :更大

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

关于c++ - std::greater<int>()(100, 300),为什么它有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32967947/

相关文章:

c++ - 在运行时定义 C++ 函数

c++ - 封装在头文件中

c++ - C++ 中的简单仿函数,STL

haskell - 在记录上映射身份仿函数

c++ - C++中是否有浮点文字后缀来使数字 double ?

c++ - 与模板类的链接错误

haskell - Haskell 中的 Representable 用于什么?

c++ - 一个类的方法覆盖另一个类的所有方法

c++ - 有什么方法可以免费获得 Borland 的 Turbo C++ 编译器的古董版本?

c++ - 使用枚举成员值检查变量值的优化方法