Policy-based design
   HOME

TheInfoList



OR:

''Modern C++ Design: Generic Programming and Design Patterns Applied'' is a book written by
Andrei Alexandrescu Andrei 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 articulated ...
, published in 2001 by
Addison-Wesley Addison-Wesley is an American publisher of textbooks and computer literature. It is an imprint of Pearson PLC, a global publishing and education company. In addition to publishing books, Addison-Wesley also distributes its technical titles throu ...
. It has been regarded as "one of the most important C++ books" by
Scott Meyers Scott Douglas Meyers (born April 9, 1959) is an American author and software consultant, specializing in the C++ computer programming language. He is known for his ''Effective C++'' book series. During his career, he was a frequent speaker at co ...
. The book makes use of and explores a
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
programming technique called
template metaprogramming Template metaprogramming (TMP) is a metaprogramming technique in which templates are used by a compiler to generate temporary source code, which is merged by the compiler with the rest of the source code and then compiled. The output of these t ...
. 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. 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 for C++ known as policies. It has been described as a
compile-time In computer science, compile time (or compile-time) describes the time window during which a computer program is compiled. The term is used as an adjective to describe concepts related to the context of program compilation, as opposed to concept ...
variant of the
strategy pattern In computer programming, the strategy pattern (also known as the policy pattern) is a behavioral software design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives run-time in ...
, and has connections with C++
template metaprogramming Template metaprogramming (TMP) is a metaprogramming technique in which templates are used by a compiler to generate temporary source code, which is merged by the compiler with the rest of the source code and then compiled. The output of these t ...
. 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 translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primarily used for programs tha ...
with highly
robust Robustness is the property of being strong and healthy in constitution. When it is transposed into a system, it refers to the ability of tolerating perturbations that might affect the system’s functional body. In the same line ''robustness'' ca ...
support for
template Template may refer to: Tools * Die (manufacturing), used to cut or shape material * Mold, in a molding process * Stencil, a pattern or overlay used in graphic arts (drawing, painting, etc.) and sewing to replicate letters, shapes or designs ...
s, 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 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 Interface or interfacing may refer to: Academic journals * ''Interface'' (journal), by the Electrochemical Society * '' Interface, Journal of Applied Linguistics'', now merged with ''ITL International Journal of Applied Linguistics'' * '' Int ...
(called a ''policy''), and encapsulating some orthogonal (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 materials, books or media that are accessible for use and not just for display purposes. A library provides physical (hard copies) or digital access (soft copies) materials, and may be a physical location or a vir ...
or
module Module, modular and modularity may refer to the concept of modularity. They may also refer to: Computing and engineering * Modular design, the engineering discipline of designing complex devices using separately designed sub-components * Mo ...
can support an
exponential Exponential may refer to any of several mathematical topics related to exponentiation, including: *Exponential function, also: **Matrix exponential, the matrix analogue to the above *Exponential decay, decrease at a rate proportional to value *Expo ...
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 from new concept, policy-based design represents an innovation in the way it applies that concept at the (relatively low) level of defining the behavior of an individual class. Policy classes have some similarity to
callback Callback may refer to: * Callback (comedy), a joke which refers to one previously told * Callback (computer programming), executable code that is passed as a parameter to other code * Callback (telecommunications), the telecommunications event th ...
s, but differ in that, rather than consisting of a single
function Function or functionality may refer to: Computing * Function key, a type of key on computer keyboards * Function model, a structured representation of processes in a system * Function object or functor or functionoid, a concept of object-oriente ...
, a policy class will typically contain several related functions (
method Method ( grc, μέθοδος, methodos) literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In recent centuries it more often means a prescribed process for completing a task. It may refer to: *Scien ...
s), often combined with
state State may refer to: Arts, entertainment, and media Literature * ''State Magazine'', a monthly magazine published by the U.S. Department of State * ''The State'' (newspaper), a daily newspaper in Columbia, South Carolina, United States * ''Our S ...
variables or other facilities such as nested types. A policy-based host class can be thought of as a type of
metafunction The term metafunction originates in systemic functional linguistics and is considered to be a property of all languages. Systemic functional linguistics is functional and semantic rather than formal and syntactic in its orientation. As a functional ...
, 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 Multiple inheritance is a feature of some object-oriented computer programming languages in which an object or class can inherit features from more than one parent object or parent class. It is distinct from single inheritance, where an object or ...
. (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", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of ...
, policies invert the relationship between
base class In object-oriented programming, inheritance is the mechanism of basing an object or class upon another object ( prototype-based inheritance) or class ( class-based inheritance), retaining similar implementation. Also defined as deriving new classe ...
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, but rather is defined implicitly, via
duck typing Duck typing in computer programming is an application of the duck test—"If it walks like a duck and it quacks like a duck, then it must be a duck"—to determine whether an object can be used for a particular purpose. With nominative ty ...
, and must be documented separately and manually, in
comment Comment may refer to: * Comment (linguistics) or rheme, that which is said about the topic (theme) of a sentence * Bernard Comment (born 1960), Swiss writer and publisher Computing * Comment (computer programming), explanatory text or informa ...
s. 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 In object-oriented programming, the template method is one of the behavioral design patterns identified by Gamma et al. in the book ''Design Patterns''. The template method is a method in a superclass, usually an abstract superclass, and defines ...
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 Concepts are defined as abstract ideas. They are understood to be the fundamental building blocks of the concept behind principles, thoughts and beliefs. They play an important role in all aspects of cognition. As such, concepts are studied by s ...
in future versions of C++.


Simple example

Presented below is a simple (contrived) example of a C++
hello world program ''Hello'' is a salutation or greeting in the English language. It is first attested in writing from 1826. Early uses ''Hello'', with that spelling, was used in publications in the U.S. as early as the 18 October 1826 edition of the '' Norwich ...
, 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 the name of a
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
software library In computer science, a library is a collection of non-volatile resources used by computer programs, often for software development. These may include configuration data, documentation, help data, message templates, pre-written code and sub ...
written by
Andrei Alexandrescu Andrei 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 articulated ...
as part of his book ''Modern C++ Design''. The library makes extensive use of C++
template metaprogramming Template metaprogramming (TMP) is a metaprogramming technique in which templates are used by a compiler to generate temporary source code, which is merged by the compiler with the rest of the source code and then compiled. The output of these t ...
and implements several commonly used tools: typelist,
functor In mathematics, specifically category theory, a functor is a mapping between categories. Functors were first considered in algebraic topology, where algebraic objects (such as the fundamental group) are associated to topological spaces, and m ...
,
singleton Singleton may refer to: Sciences, technology Mathematics * Singleton (mathematics), a set with exactly one element * Singleton field, used in conformal field theory Computing * Singleton pattern, a design pattern that allows only one instance ...
, smart pointer, object factory, visitor and multimethods. Originally the library was only compatible with two of the most standard conforming C++ compilers (
CodeWarrior CodeWarrior is an integrated development environment (IDE) published by NXP Semiconductors for editing, compiling, and debugging software for several microcontrollers and microprocessors (Freescale ColdFire, ColdFire+, Kinetis, Qorivva, PX, Frees ...
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 C, C++, Objective-C, and Objective-C++ programming languages, as well as the OpenMP, OpenCL, RenderScript, CUDA, and HIP frameworks. It acts as a drop-in replacement for the GNU Compiler Collection ...
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
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

* Boost (C++ libraries) *
Mixin In object-oriented programming languages, a mixin (or mix-in) is a class that contains methods for use by other classes without having to be the parent class of those other classes. How those other classes gain access to the mixin's methods depen ...


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++