在 C++11 中,您可以使用std::bind
; 如何使用它并不那么明显:
#include <functional>
using namespace std::placeholders;
std::find_if(
foo.begin(),
foo.end(),
// create a unary function object that invokes greater<int>::operator()
// with the single parameter passed as the first argument and `bar`
// passed as the second argument
std::bind(std::greater<int>(), _1, bar)
) - foo().begin() - 1;
关键是使用在std::placeholders
命名空间中声明的占位符参数。std::bind
返回一个函数对象,该对象在调用时接受一定数量的参数。调用内部使用的占位符std::bind
显示调用结果对象时提供的参数如何映射到要绑定的可调用对象的参数列表。因此,例如:
auto op1 = std::bind(std::greater<int>(), _1, bar);
op1(5); // equivalent to std::greater<int>()(5, bar)
auto op2 = std::bind(std::greater<int>(), bar, _1);
op2(5); // equivalent to std::greater<int>()(bar, 5)
auto op3 = std::bind(std::greater<int>(), _2, _1);
op3(5, bar); // equivalent to std::greater<int>()(bar, 5)
auto op4 = std::bind(std::greater<int>(), _1, _2);
op4(5, bar); // equivalent to std::greater<int>()(5, bar)