Policy
Thanks to templates, there are new ways of software design. Policies and traits are two commonly used idioms in C++.
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 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.
Modernes C++ Mentoring
Do you want to stay informed: Subscribe.
// 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 or the equal function.
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 myMa
p.
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
.
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 over 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, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, 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, Stephen Kelley, Kyle Dean, Tusar Palauri, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, Marco Parri Empoli, Philipp Lenk, Charles-Jianye Chen, Keith Jeffery, Matt Godbolt, and Honey Sukesan.
Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.
My special thanks to Embarcadero | |
My special thanks to PVS-Studio | |
My special thanks to Tipi.build | |
My special thanks to Take Up Code | |
My special thanks to SHAVEDYAKS |
Modernes C++ GmbH
Modernes C++ Mentoring (English)
Rainer Grimm
Yalovastraße 20
72108 Rottenburg
Mail: schulung@ModernesCpp.de
Mentoring: www.ModernesCpp.org
Modernes C++ Mentoring,
Leave a Reply
Want to join the discussion?Feel free to contribute!