Listing 3: Providing a user-definable policy via specialization of a function template
// //---- begin file library.h ---- // #include <iostream> template<class Container> void policy(const Container * c) { std::cout << "Performing Default Policy" << std::endl << std::endl; } // //---- begin file container.h ---- // #include "library.h" #include <string> #include <iostream> template <class ElementType> class MyContainer { public: MyContainer(const std::string iName) : instanceName(iName) {} // class implementation // ... // forwards the policy request void doPolicy(); // a service that uses the policy void performService() { doPolicy(); } const std::string instanceName; }; // elements for example's sake template<class T> struct Element1 { // ... }; template<class T> struct Element2 { // ... }; template <class ElementType> void MyContainer<ElementType>::doPolicy() { policy(this); } // //---- begin file user.cpp ---- // #include "container.h" template<class T> void policy(const MyContainer<Element2<T> > * c) { std::cout << "Performing My Policy" << std::endl << std::endl; } int main() { MyContainer<Element1<int> > c("object1"); MyContainer<Element2<int> > d("object2"); c.doPolicy(); d.doPolicy(); return 0; } End of Listing