让你的 bool_xxx 函数实际上是特定类型的函子(标签调度就足够了)。然后覆盖 ||和 && 以便这些运算符返回 bool_and 或 bool_or。然后你可以像这样使用 bool_ 谓词:
std::find_if(vect.begin(), vect.end(), bool_x1() || bool_x2() && (bool_x3() || bool_x4() && bool_x5()));
如果您想编写一个“where”函数,那么您显然希望使用一组不同的 bool_xxx 函数多次执行此操作。即使你知道你现在想要某种类型的作品,你也可以让它尽可能通用。我就是这样做的。
Edit:
基于此评论:@Jerry:例如我需要知道: id=where(v 1.0);稍后我想知道: id=where(v 你可能会更好地使用 boost::lambda:
namespace l = boost::lambda;
std::find_if(vect.begin(), vect.end(), l::_1 < 10.0 && l::_1 > 1.0);
std::find_if(vect.begin(), vect.end(), l::_1 < l::bind(fun, l::_1));
或者,如果您讨厌 lambda 或不允许使用它...或者只是想要一个稍微好一点的语法(但无法直接使用函数),那么只需创建您自己的占位符类型并覆盖它以在运算符 等...
Edit2:这是一个未经测试的地方,它将迭代器向量返回到所有匹配的对象:
template < typename ForwardIter, typename Predicate >
std::vector<ForwardIter> where(ForwardIter beg, ForwardIter end, Predicate pred)
{
ForwardIter fit = std::find_if(beg,end,pred);
if (fit == end) return std::vector<ForwardIter>();
ForwardIter nit = fit; ++nit;
std::vector<ForwardIter> collection = where(nit,end,pred);
collection.push_front(fit);
return collection;
}
它是递归的,在某些实现上可能会很慢,但有一种方法可以做到这一点。