Reputation: 872
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?
Upvotes: 1
Views: 252
Reputation: 76276
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) someObj
does not change it's mind on what to return from someObj::someFn
for particular instances of T2
it 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).
Upvotes: 2
Reputation: 17329
Yes, that's fine.
Just make sure that the entire operation provides whatever stability requirements the sort needs.
Upvotes: 1