用于普通操作的STD一元函数

std unary functions for common operations

本文关键字:一元 函数 STD 操作 用于      更新时间:2023-10-16

是否有理由不为函数中的二进制函数提供一元版本?

我知道通过使用std::bind创建一元版本很简单,但是代码看起来很难看:

std::find_if(std::begin(v), std::end(v), std::bind(std::less_equal<int>(), std::placeholders::_1, 42));

我想如果有这样的东西会更好:

std::find_if(std::begin(v), std::end(v), std::less_equal<int>(42));

IMHO自c++ 11/14以来,lambda使这种谓词变得多余?

find_if(begin(v), end(v), [](auto x){ return x <= 42; });

我认为没有技术上的理由不允许你的第二种方法。在弃用之前,std::bind2nd辅助函数将非常接近您想要的方法:

std::find_if(std::begin(v), std::end(v), std::bind2nd(std::less_equal<int>(), 42));

当然你也可以创建自己的helper——它很短:

template <typename T> auto cmp_less_equal(const T& x) {
  return std::bind(std::less_equal<T>(), std::placeholders::_1, x);
}

现在你可以写

std::find_if(std::begin(v), std::end(v), cmp_less_equal(42));

使用你自己的包装器

给lambda一个名字怎么样?

const auto cmp_less_eq = [](auto x){ return x <= 42; };
const auto result = find_if(begin(v), end(v), cmp_less_eq);