La mejor solución es usar el STL functional library. Al derivar su predicado de unary_function<SomeType, bool>
, entonces podrá usar la función not1
, que hace exactamente lo que necesita (es decir, negando un predicado unario).
Aquí es cómo se puede hacer eso:
struct FindPredicate : public unary_function<SomeType, bool>
{
FindPredicate(const SomeType& t) : _t(t) {}
bool operator()(const SomeType& t) const {
return t == _t;
}
private:
const SomeType& _t;
};
bool AllSatisfy(std::vector<SomeType>& v, SomeType& valueToFind)
{
return find_if(v.begin(),
v.end(),
not1(FindPredicate(valueToFind))) == v.end();
}
Si quieren rodar su propia solución (que es, en mi humilde opinión, no es la mejor opción ...), así, se podría escribir otro predicado que es la negación de la primera:
struct NotFindPredicate
{
NotFindPredicate(const SomeType& t) : _t(t) {
}
bool operator()(SomeType& t) {
return t != _t;
}
private:
const SomeType& _t;
};
bool AllSatisfy(std::vector<SomeType>& v) {
return find_if(v.begin(),
v.end(),
NotFindPredicate(valueToFind)) == v.end();
}
O se podría hacer mejor y escribir un negador plantilla funtor, como:
template <class Functor>
struct Not
{
Not(Functor & f) : func(f) {}
template <typename ArgType>
bool operator()(ArgType & arg) { return ! func(arg); }
private:
Functor & func;
};
que se puede utilizar de la siguiente manera:
bool AllSatisfy(std::vector<SomeType>& v, SomeType& valueToFind)
{
FindPredicate f(valueToFind);
return find_if(v.begin(), v.end(), Not<FindPredicate>(f)) == v.end();
}
Por supuesto, esta última solución es mejor porque se puede volver a utilizar la estructura No con cada funtor que desea.
Y entonces se podría agregar una función de plantilla cuña como la gente de la SGI hicieron para devolver un objeto no sin tener que especificar su tipo. –
xtofl