Policy-based design
   HOME

TheInfoList



OR:

''Modern C++ Design: Generic Programming and Design Patterns Applied'' is a book written by
Andrei Alexandrescu Tudor Andrei Cristian Alexandrescu (born 1969) is a Romanian-American C++ and D language programmer and author. He is particularly known for his pioneering work on policy-based design implemented via template metaprogramming. These ideas are a ...
, published in 2001 by Addison-Wesley. It has been regarded as "one of the most important C++ books" by Scott Meyers. The book makes use of and explores a C++ programming technique called template metaprogramming. While Alexandrescu didn't invent the technique, he has popularized it among programmers. His book contains solutions to practical problems which C++ programmers may face. Several phrases from the book are now used within the C++ community as generic terms: ''modern C++'' (as opposed to C/C++ style), policy-based design and typelist. All of the code described in the book is freely available in his library
Loki Loki is a Æsir, god in Norse mythology. He is the son of Fárbauti (a jötunn) and Laufey (mythology), Laufey (a goddess), and the brother of Helblindi and Býleistr. Loki is married to the goddess Sigyn and they have two sons, Narfi (son of Lo ...
. The book has been republished and translated into several languages since 2001.


Policy-based design

Policy-based design, also known as policy-based class design or policy-based programming, is the term used in ''Modern C++ Design'' for a design approach based on an
idiom An idiom is a phrase or expression that largely or exclusively carries a Literal and figurative language, figurative or non-literal meaning (linguistic), meaning, rather than making any literal sense. Categorized as formulaic speech, formulaic ...
for C++ known as policies. It has been described as a compile-time variant of the strategy pattern, and has connections with C++ template metaprogramming. It was first popularized in C++ by Andrei Alexandrescu with ''Modern C++ Design'' and with his column ''Generic'' in the '' C/C++ Users Journal'', and it is currently closely associated with C++ and D as it requires a
compiler In computing, a compiler is a computer program that Translator (computing), translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primaril ...
with highly robust support for templates, which was not common before about 2003. Previous examples of this design approach, based on parameterized generic code, include parametric modules (functors) of the ML languages, and C++ allocators for memory management policy. The central idiom in policy-based design is a
class Class, Classes, or The Class may refer to: Common uses not otherwise categorized * Class (biology), a taxonomic rank * Class (knowledge representation), a collection of individuals or objects * Class (philosophy), an analytical concept used d ...
template (called the ''host'' class), taking several type
parameter A parameter (), generally, is any characteristic that can help in defining or classifying a particular system (meaning an event, project, object, situation, etc.). That is, a parameter is an element of a system that is useful, or critical, when ...
s as input, which are instantiated with types selected by the user (called ''policy classes''), each implementing a particular implicit interface (called a ''policy''), and encapsulating some
orthogonal In mathematics, orthogonality (mathematics), orthogonality is the generalization of the geometric notion of ''perpendicularity''. Although many authors use the two terms ''perpendicular'' and ''orthogonal'' interchangeably, the term ''perpendic ...
(or mostly orthogonal) aspect of the behavior of the instantiated host class. By supplying a host class combined with a set of different, canned implementations for each policy, a
library A library is a collection of Book, books, and possibly other Document, materials and Media (communication), media, that is accessible for use by its members and members of allied institutions. Libraries provide physical (hard copies) or electron ...
or module can support an exponential number of different behavior combinations, resolved at compile time, and selected by mixing and matching the different supplied policy classes in the instantiation of the host class template. Additionally, by writing a custom implementation of a given policy, a policy-based library can be used in situations requiring behaviors unforeseen by the library implementor. Even in cases where no more than one implementation of each policy will ever be used, decomposing a class into policies can aid the design process, by increasing modularity and highlighting exactly where orthogonal design decisions have been made. While assembling software components out of interchangeable modules is a far-fetched concept, policy-based design represents an innovation in a way it applies that concept at the (relatively low) level of defining the behavior of an individual class. Policy classes are similar to callbacks, but differ in that, rather than consisting of a single function, a policy class will typically contain several related functions ( methods), often combined with state variables or other facilities such as nested types. A policy-based host class can be thought of as a type of metafunction, taking a set of behaviors represented by types as input, and returning as output a type representing the result of combining those behaviors into a functioning whole. (Unlike MPL metafunctions, however, the output is usually represented by the instantiated host class itself, rather than a nested output type.) A key feature of the ''policy'' idiom is that, usually (though it is not strictly necessary), the host class will derive from (make itself a child class of) each of its policy classes using (public) multiple inheritance. (Alternatives are for the host class to merely contain a member variable of each policy class type, or else to inherit the policy classes privately; however, inheriting the policy classes publicly has the major advantage that a policy class can add new methods, inherited by the instantiated host class and accessible to its users, which the host class itself need not even know about.) A notable feature of this aspect of the policy idiom is that, relative to
object-oriented programming Object-oriented programming (OOP) is a programming paradigm based on the concept of '' objects''. Objects can contain data (called fields, attributes or properties) and have actions they can perform (called procedures or methods and impl ...
, policies invert the relationship between base class and derived class - whereas in OOP interfaces are traditionally represented by ( abstract) base classes and implementations of interfaces by derived classes, in policy-based design the derived (host) class represents the interfaces and the base (policy) classes implement them. In the case of policies, the public inheritance does not represent an is-a relationship between the host and the policy classes. While this would traditionally be considered evidence of a design defect in OOP contexts, this doesn't apply in the context of the policy idiom. A disadvantage of policies in their current incarnation is that the policy interface doesn't have a direct, explicit representation in
code In communications and information processing, code is a system of rules to convert information—such as a letter, word, sound, image, or gesture—into another form, sometimes shortened or secret, for communication through a communicati ...
, but rather is defined implicitly, via duck typing, and must be documented separately and manually, in comments. The main idea is to use commonality-variability analysis to divide the type into the fixed implementation and interface, the policy-based class, and the different policies. The trick is to know what goes into the main class, and what policies should one create. The article mentioned above gives the following answer: wherever we would need to make a possible limiting design decision, we should postpone that decision, we should delegate it to an appropriately named policy. Policy classes can contain implementation, type definitions and so forth. Basically, the designer of the main template class will define what the policy classes should provide, what customization points they need to implement. It may be a delicate task to create a good set of policies, just the right number (e.g., the minimum necessary). The different customization points, which belong together, should go into one policy argument, such as storage policy, validation policy and so forth. Graphic designers are able to give a name to their policies, which represent concepts, and not those which represent operations or minor implementation details. Policy-based design may incorporate other useful techniques. For example, the template method pattern can be reinterpreted for compile time, so that a main class has a skeleton algorithm, whichat customization pointscalls the appropriate functions of some of the policies. This will be achieved dynamically by concepts in future versions of C++.


Simple example

Presented below is a simple (contrived) example of a C++ hello world program, where the text to be printed and the method of printing it are decomposed using policies. In this example, ''HelloWorld'' is a host class where it takes two policies, one for specifying how a message should be shown and the other for the actual message being printed. Note that the generic implementation is in Run and therefore the code is unable to be compiled unless both policies (Print and Message) are provided. #include #include template class HelloWorld : private OutputPolicy, private LanguagePolicy ; class OutputPolicyWriteToCout ; class LanguagePolicyEnglish ; class LanguagePolicyGerman ; int main() Designers can easily write more OutputPolicys by adding new classes with the member function Print and take those as new OutputPolicys.


Loki library

Loki is a C++ software library written by
Andrei Alexandrescu Tudor Andrei Cristian Alexandrescu (born 1969) is a Romanian-American C++ and D language programmer and author. He is particularly known for his pioneering work on policy-based design implemented via template metaprogramming. These ideas are a ...
as part of his book ''Modern C++ Design''. The library makes extensive use of C++ template metaprogramming and implements several commonly used tools: typelist,
functor In mathematics, specifically category theory, a functor is a Map (mathematics), mapping between Category (mathematics), categories. Functors were first considered in algebraic topology, where algebraic objects (such as the fundamental group) ar ...
, singleton, smart pointer, object factory, visitor and multimethods. Originally the library was only compatible with two of the most standard conforming C++ compilers ( CodeWarrior and Comeau C/C++): later efforts have made it usable with a wide array of compilers (including older Visual C++ 6.0, Borland C++ Builder 6.0,
Clang Clang () is a compiler front end for the programming languages C, C++, Objective-C, Objective-C++, and the software frameworks OpenMP, OpenCL, RenderScript, CUDA, SYCL, and HIP. It acts as a drop-in replacement for the GNU Compiler ...
and GCC). Compiler vendors used Loki as a compatibility benchmark, further increasing the number of compliant compilers.C++ and Beyond 2011: "Ask Us Anything" session, http://channel9.msdn.com/Shows/Going+Deep/C-and-Beyond-2011-Scott-Andrei-and-Herb-Ask-Us-Anything at 51:40-51:51 Maintenance and further development of Loki has been continued through an open-source community led by Peter Kümmel and Richard Sposato as a SourceForge project. Ongoing contributions by many people have improved the overall robustness and functionality of the library. Loki is not tied to the book anymore as it already has a lot of new components (e.g. StrongPtr, Printf, and Scopeguard). Loki inspired similar tools and functionality now also present in the Boost library collection.


See also

* Mixin


References


External links


Alexandrescu's website
(with book errat


Smart Pointers
(sample chapter from the book) * {{SourceForge, loki-lib, Loki
Original source code from the book publisher
2001 non-fiction books Books about C++