(C++) Policy

January 8, 2018 · View on GitHub

 

 

 

 

 

(C++) Policy

 

A policy is a class behaviour set at compile-time.

 

A policy consts of a host class and policy classes. The user of a policy chooses which policy class is used, by template.

 

A policy class is a base class. All base class destructors should be public and virtual, or protected and nonvirtual' [1]. The destructor of a policy class should be protected and nonvirtual [2].

 

 

 

 

 

Example

 

During debugging, you might want to trace (keep track of) variables.

Sometimes, you might want to write it to std::cout, file or other ways.

The example below shows a Tracer class, whose behavior is set at compile-time.

 


#include <iostream> #include <fstream> #include <string> template <typename OutputPolicy> struct Tracer : public OutputPolicy { }; struct OutputPolicyCout {   void Trace(const std::string& s)   {     std::cout << s << '\n';   } protected:   ~OutputPolicyCout()   {     // The destructor of a policy class should be protected and non-virtual [1].   } }; struct OutputPolicyFile {   OutputPolicyFile() : m_file("Trace.txt")   {   }   void Trace(const std::string& s)   {     m_file << s << '\n';   }   std::ofstream m_file; protected:   ~OutputPolicyFile()   {     // The destructor of a policy class should be protected and non-virtual [2].   } }; int main() {   Tracer<OutputPolicyCout> p1;   Tracer<OutputPolicyFile> p2;   p1.Trace("x");   p2.Trace("x"); }

 

In this example, Tracer is the host class, where OutputPolicyCout and OutputPolicyFile are policy classes.

 

Note that p1 and p2 have types as different as std::vectors with different elements.

 

 

 

 

 

References

 

  1. Herb Sutter, Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. ISBN: 0-32-111358-6. Item 50: 'Make base class destructors public and virtual, or protected and nonvirtual'
  2. Andrei Alexandrescu. Modern C++ Design. 2001. ISBN: 0201704315. Page 13. Section 1.7: 'The lightweight, effective solution that policies should use is to define a nonvirtual protected destructor'