如何使用binder2nd、bind2nd和bind1st?更具体地说,什么时候使用它们,它们是必要的吗?另外,我正在寻找一些例子。
发布于 2009-09-21 16:18:31
严格地说,它们从来都不是必需的,因为您总是可以定义自己的自定义函数器对象;但是它们非常方便,以便在简单的情况下避免必须定义自定义函数器。例如,假设您想要计算std::vector<int>中为> 10的项的数量。您当然可以编写代码...:
std::count_if(v.begin(), v.end(), gt10()) 定义后:
class gt10: std::unary_function<int, bool>
{
public:
result_type operator()(argument_type i)
{
return (result_type)(i > 10);
}
};但是想一想它对编码是多么的方便:
std::count_if(v.begin(), v.end(), std::bind1st(std::less<int>(), 10)) 不需要定义任何辅助函数器类!-)
发布于 2009-09-21 18:00:42
绑定器是执行currying的C++方式。顺便说一句,查看Boost Bind库
https://stackoverflow.com/questions/1455333
复制相似问题