22.7 Using Your oOn Functors in OEChem

While many predefined functors exist it is not difficult to find a situation which calls for a new functor. Acquiring a complete understanding of functors can be daunting, but generating a functor to pass to OEChem functions is less difficult.

The following example shows a user defined functor which screens for atoms whose atomic mass is greater than 15. Some OEMolBase methods, such as GetAtoms , have been overloaded to accept a predicate as an argument. See the API Manual for more information.

 1 #include "openeye.h"
 2 #include "oechem.h"
 3 #include "oesystem.h"
 4
 5 #include <iostream>
 6
 7 using namespace OESystem;
 8 using namespace OEChem;
 9 using namespace std;
10
11 class WeightGT15 : public OEUnaryPredicate<OEAtomBase>
12 {
13 public:
14   bool operator()(const OEAtomBase &atom) const
15   {
16     return OEGetAverageWeight(atom.GetAtomicNum()) > 15;
17   }
18   OEUnaryFunction<OEAtomBase,bool> *CreateCopy() const
19   {
20     return new WeightGT15;
21   }
22 protected:
23   bool Eval(const OEAtomBase &atom) const { return operator()(atom); }
24   bool Eval(const OEAtomBase &)           { return false; }
25 };
26
27
28 int main()
29 {
30   OEGraphMol mol;
31   OEParseSmiles(mol, "c1c(O)c(O)c(Cl)cc1CCCBr");
32
33   OEIter<OEAtomBase> atom;
34   for(atom = mol.GetAtoms(WeightGT15());atom;++atom)
35     cout << atom->GetName() << " has weight > 15." << endl;
36
37   return 0;
38 }

Listing:22.2 User defined functors can be simple