Applicative Operator Functors
The amount of code required to write PETE is greatly reduced through the use of applicative operator functors. These functor classes overload operator() to perform the desired operation. They allow us to construct generic classes, such as BinaryNode, that work with arbitrary operators, thus greatly reducing code duplication. Due to their generic nature, these functors can be a bit tricky to write. For example, OpMultiply's operator() looks like:
template<class T1, class T2>
inline typename
BinaryReturn<T1, T2, OpMultiply>::Type_t
OpMultiply::operator()(const T1 &a,
constT2 &b) const
{ return (a * b); }
The return type is generated by the BinaryReturn traits class using the two input types and the operation type. Therefore, if T1 is an int and T2 is a double (as in the "2 * C" part of the expression in Figure 1), this function will do the correct promotion to double. PETE knows how to perform operations on the built-in C++ types, so an expression involving vector<int> and vector<double> objects requires no special code. Moreover, adding new types and operations involves only a few specializations.
--S.H.
Copyright © 1999, Dr. Dobb's Journal