Policy

Contents[Show]

Thanks to templates, there are new ways of software design. Policies and traits are two commonly used idioms in C++.

 PolicyAndTraits

Policy and traits are often used in one sentence. Let me start with policies.

Policy

A policy is a generic function or class whose behavior can be configured. Typically, there are default values for the policy parameters. std::vector and std::unordered_map exemplifies this.

template<class T, class Allocator = std::allocator<T>>          // (1)
class vector; 

template<class Key,
    class T,
    class Hash = std::hash<Key>,                               // (3)
    class KeyEqual = std::equal_to<Key>,                       // (4)
    class allocator = std::allocator<std::pair<const Key, T>>  // (2)
class unordered_map;

 

This means each container has a default allocator for its elements depending on T (line 1) or on std::pair<const Key, T> (line 2). Additionally, std::unorderd_map has a default hash function (line 3) and a default equal function (4). The hash function calculates the hash value based on the key and the equal function deals with collisions in the buckets. My previous post "Hash Functions" gives you more information about std::unordered_map.

Let me use a user-defined data type MyInt as a key in a std::unordered_map.

// MyIntAsKey.cpp

#include <iostream>
#include <unordered_map>

struct MyInt{
    explicit MyInt(int v):val(v){}
    int val;
};

int main(){

    std::cout << '\n';

    std::unordered_map<MyInt, int> myMap{ {MyInt(-2), -2}, {MyInt(-1), -1}, 
                                          {MyInt(0), 0}, {MyInt(1), 1} };

    std::cout << "\n\n";

}

 

The compilation fails pretty wordily because MyInt does not support the hash function nor the equal function.

MyIntAsKey

Now, the policy kicks in. You can replace the policy parameters. The following class MyInt can, therefore, be used as a key in a std::unordered_map.

 

// templatesPolicy.cpp

#include <iostream>
#include <unordered_map>

struct MyInt{
    explicit MyInt(int v):val(v){}
    int val;
};

struct MyHash{                                                        // (1)
    std::size_t operator()(MyInt m) const {
        std::hash<int> hashVal;
        return hashVal(m.val);
    }
};

struct MyEqual{
    bool operator () (const MyInt& fir, const MyInt& sec) const {      // (2)
        return fir.val == sec.val;
    }
};

std::ostream& operator << (std::ostream& strm, const MyInt& myIn){     // (3)
    strm << "MyInt(" << myIn.val << ")";
    return strm;
}

int main(){

    std::cout << '\n';

    typedef std::unordered_map<MyInt, int, MyHash, MyEqual> MyIntMap;  // (4)

    std::cout << "MyIntMap: ";
    MyIntMap myMap{{MyInt(-2), -2}, {MyInt(-1), -1}, {MyInt(0), 0}, {MyInt(1), 1}};

    for(auto m : myMap) std::cout << '{' << m.first << ", " << m.second << "}";

    std::cout << "\n\n";

}

 

I implemented the hash function (line 1), and the equal function (line 2) as a function object, and overloaded, for convenience reasons, the output operator (line 3). Line 4 creates out of all components a new type MyIntMap that uses MyInt as key. The following screenshot shows the output of the instance myMap.

templatesPolicy

There are two typical ways to implement policies: composition and inheritance.

Composition

The following class Message uses composition to configure its output device during compile time.

// policyComposition.cpp

#include <iostream>
#include <fstream>
#include <string>

template <typename OutputPolicy>                    // (1)
class Message {
 public:
    void write(const std::string& mess) const {
        outPolicy.print(mess);                      // (2)
    }
 private:
    OutputPolicy outPolicy;   
};

class WriteToCout {                                 // (5)
 public:
    void print(const std::string& message) const {
        std::cout << message << '\n';
    }
};

class WriteToFile {                                 // (6)
 public:
    void print(const std::string& message) const {
        std::ofstream myFile;
        myFile.open("policyComposition.txt");
        myFile << message << '\n';
    }
};


int main() {

    Message<WriteToCout> messageCout;              // (3)
    messageCout.write("Hello world");

    Message<WriteToFile> messageFile;              // (4)
    messageFile.write("Hello world");

}

 

The class Message has the template parameter OutputPolicy (line 1) as policy. A call of its member function write delegates directly to its member outPolicy (line 2). You can create two different Message instances (lines 3 and 4). One writing to count (line 5), and one writing to a file (line 6).

The screenshot shows the write operation to cout and the file policyComposition.txt.

policyComposition

Inheritance

The inheritance based implementation is quite similar to the composite based in the file policyComposition.cpp. The main difference is that the composite-based implementation has the policy, but the inheritance-based implementation derives from its policy.

 

// policyInheritance.cpp

#include <iostream>
#include <fstream>
#include <string>

template <typename OutputPolicy>                  
class Message : private OutputPolicy {            // (1) 
 public:
    void write(const std::string& mess) const {
        print(mess);                              // (2)
    }
 private:
    using OutputPolicy::print;
};

class WriteToCout {
 protected:
    void print(const std::string& message) const {
        std::cout << message << '\n';
    }
};

class WriteToFile {
 protected:
    void print(const std::string& message) const {
        std::ofstream myFile;
        myFile.open("policyInheritance.txt");
        myFile << message << '\n';
    }
};


int main() {

    Message<WriteToCout> messageCout;
    messageCout.write("Hello world");

    Message<WriteToFile> messageFile;
    messageFile.write("Hello world");

}

 

Instead of the previous implementation of the class Message, this one derives from its template parameter privately and introduces the private inherited print function into the class scope. I skip the output of the program for obvious reasons. Okay. I hear your question: Should I use composition or inheritance for implementing a policy-based design?

Composition or Inheritance

In general, I prefer composition above inheritance. In general, but for a policy-based design you should consider inheritance.

If  OutputPolicy is empty, you can benefit from the so-called empty base class optimization. Empty means that OutputPolicy has no non-static data members, and no non-empty base classes. Consequentially, OutputPolicy does not add anything to the size of Message. On the contrary, when Message has the member OutputPolicy, OutputPolicy adds at least one byte to the size of Message. My argument may not sound convincing, but often a class uses more than one policy.

What's next?

Traits are class templates that pull properties out of a generic type. I will write more about them in my next post.

 

Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, Marko, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, Louis St-Amour, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Neil Wang, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Evangelos Denaxas, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Ralf Holly, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, and Stephen Totten.

 

Thanks in particular to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, Ralf Abramowitsch, John Nebel, and Mipko.

 

 

My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small

 

My special thanks to PVS-Studio PVC Logo

 

Mentoring Program in English

Do you want to stay informed about my mentoring programs? Write to This email address is being protected from spambots. You need JavaScript enabled to view it..

Seminars

I'm happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

Bookable (Online)

German

Standard Seminars (English/German)

Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.

New

Contact Me

Modernes C++,

RainerGrimmDunkelBlauSmall

Mentoring: Fundamentals for C++ Professionals

English Books

Course: Modern C++ Concurrency in Practice

Course: C++ Standard Library including C++14 & C++17

Course: Embedded Programming with Modern C++

Course: Generic Programming (Templates)

Course: C++ Fundamentals for Professionals

Interactive Course: The All-in-One Guide to C++20

Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code

Visitors

Today 8525

Yesterday 5357

Week 8525

Month 58872

All 9999119

Currently are 196 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments