template class A1, class A2> void apply(Seq& sq, R(T::*f)(A1, A2), A1 a1, A2 a2) { typename Seq::iterator it = sq.begin(); while(it != sq.end()) { ((*it)->*f)(a1, a2); it++; } } // Etc., to handle maximum likely arguments ///:~ The apply( ) function template takes a reference to the container class and a pointer-to-member for a member function of the objects contained in the class. It uses an iterator to move through the Stack and apply the function to every object. Notice that there are no STL header files (or any header files, for that matter) included in applySequence.h, so it is actually not limited to use with an STL container. However, it does make assumptions (primarily, the name and behavior of the iterator) that apply to STL sequences. You can see there is more than one version of apply( ), further illustrating overloading of function templates. Although these templates allow any type of return value (which is ignored, but the type information is required to match the pointer-to-member), each version takes a different number of arguments, and because it’s a template, those arguments can be of any type. The only limitation here is that there’s no "super template" to create templates for you; you must decide how many arguments will ever be required. To test the various overloaded versions of apply( ), the class Gromit[57] is created containing functions with different numbers of arguments:. //: C05:Gromit.h // The techno-dog. Has member functions // with various numbers of arguments. #include class Gromit { int arf; public: Gromit(int arf = 1) : arf(arf + 1) {} void speak(int) { for(int i = 0; i < arf; i++) std::cout << "arf! "; std::cout << std::endl; } char eat(float) { std::cout << "chomp!" << std::endl; return 'z'; } int sleep(char, double) { std::cout << "zzz..." << std::endl; return 0; } void sit() { std::cout << " Sitting...)" << std::endl; } }; ///:~ Now you can use the apply( ) template functions to apply the Gromit member functions to a vector //: C05:ApplyGromit.cpp // Test ApplySequence.h #include #include #include #include "ApplySequence.h" #include "Gromit.h" using namespace std; int main() { vector for(size_t i = 0; i < 5; i++) dogs.push_back(new Gromit(i)); apply(dogs, &Gromit::speak, 1); apply(dogs, &Gromit::eat, 2.0f); apply(dogs, &Gromit::sleep, 'z', 3.0); apply(dogs, &Gromit::sit); for (size_t i = 0; i < dogs.size(); ++i) delete dogs[i]; } ///:~ Although the definition of apply( ) is somewhat complex and not something you’d ever expect a novice to understand, its use is remarkably clean and simple, and a novice could easily use it knowing only