22.5 Call-Backs

Simply stated, predicate functors (boolean functors) are functions which return "true" or "false". In OEChem, these functors are often passed into another function. The functors are then called from inside the second function. This is the concept of a "call-back" because the second function provides the argument and "call's back" to the functor which was passed into the function.

#include "oechem.h"
#include "oesystem.h"

#include <iostream>

using namespace OESystem;
using namespace OEChem;
using namespace std;

unsigned int Count(const OEUnaryPredicate<OEAtomBase> &fcn,
                   const OEMolBase &mol)
{
  unsigned int count = 0;
  OEIter<OEAtomBase> atom;
  for(atom = mol.GetAtoms();atom;++atom)
    if(fcn(*atom))
      ++count;

  return count;
}

int main()
{
  OEGraphMol mol;
  OEParseSmiles(mol, "c1c(O)c(O)c(Cl)cc1CCCBr");

  cerr << "Number of Oxygens = " << Count(OEIsOxygen(),mol) << endl;

  cerr << "Number of Carbons = " << Count(OEHasAtomicNum(6),mol) << endl;

  cerr << "Number of Halides = " << Count(OEIsHalide(),mol) << endl;

  return 0;
}

In the example above, the function Count loops over the atom and performs a call-back to the predicate functor fcn for each atom. If the predicate returns true, a counter is incremented. The main loop passes three of OEChem's predefined atom predicates to the Count function, allowing the same function to calculate the number atoms in the molecule which satisfy the functor passed to it.