Bruce Eckel's Thinking in C++, 2nd Ed | Contents | Prev | Next |
//: C19:applyMember.h // applySequence.h modified to use // member function templates template<class T, template<typename> class Seq> class SequenceWithApply : public Seq<T*> { public: // 0 arguments, any type of return value: template<class R> void apply(R (T::*f)()) { iterator it = begin(); while(it != end()) { ((*it)->*f)(); it++; } } // 1 argument, any type of return value: template<class R, class A> void apply(R(T::*f)(A), A a) { iterator it = begin(); while(it != end()) { ((*it)->*f)(a); it++; } } // 2 arguments, any type of return value: template<class R, class A1, class A2> void apply(R(T::*f)(A1, A2), A1 a1, A2 a2) { iterator it = begin(); while(it != end()) { ((*it)->*f)(a1, a2); it++; } }
//: C19:applyGromit2.cpp // Test applyMember.h #include "Gromit.h" #include "applyMember.h" #include <vector> #include <iostream> using namespace std; int main() { SequenceWithApply<Gromit, vector> dogs; for(int i = 0; i < 5; i++) dogs.push_back(new Gromit(i)); dogs.apply(&Gromit::speak, 1); dogs.apply(&Gromit::eat, 2.0f); dogs.apply(&Gromit::sleep, 'z', 3.0); dogs.apply(&Gromit::sit);