By “pure” predicates I mean they only depend on their arguments. So is the following function object a valid predicate for use in say, std::sort
// A predicate for sorting objects of type T2 that relies on an
// object of type T1.
class APredicate {
T1 &someObj;
APredicate(T1 &someObject) : someObj(someObject) {};
bool operator() (T2 thing1, T2 thing2) {
return someObj.someFn(thing1) < someobj.someFn(thing2);
}
}
Is this ever valid? Always valid? Or does it depend on what someObj.SomeFn() actually does?
The “only depends on their arguments” actually means “if called again with the same arguments, must return the same result as previously”. If your (particular instance of)
someObjdoes not change it’s mind on what to return fromsomeObj::someFnfor particular instances ofT2it is “pure”.As long as the condition holds for lifetime of the particular instance of the predicate (STL takes predicates by value, so each collection or operation have their own instance), it is correct (obviously it has to satisfy any other requirement of the particular collection or algorithm).