| Author | Andrei Alexandrescu |
|---|---|
| Language | English |
| Subject | C++ |
| Publisher | Addison-Wesley |
Publication date | 2001 |
| Pages | 323 pp |
| ISBN | 978-0-201-70431-0 |
| OCLC | 45129236 |
| 005.13/3 21 | |
| LC Class | QA76.73.C153 A42 2001 |
Modern C++ Design: Generic Programming and Design Patterns Applied is a book written byAndrei Alexandrescu, published in 2001 byAddison-Wesley. It has been regarded as "one of the most important C++ books" byScott Meyers.[1]
The book makes use of and explores aC++ programming technique calledtemplate 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++ (in contrast to C/C++ style),policy-based design, andtypelist.[citation needed]
All of the code described in the book is freely available in his libraryLoki. The book has been republished and translated into several languages since 2001.[citation needed]
Policy-based design, also known aspolicy-based class design orpolicy-based programming, is the term used inModern C++ Design for a design approach based on anidiom for C++ known aspolicies. It has been described as acompile-time variant of thestrategy pattern, and has connections with C++template metaprogramming. It was first popularized in C++ by Andrei Alexandrescu withModern C++ Design and with his columnGeneric<Programming> in theC/C++ Users Journal, and it is currently closely associated with C++ andD as it requires acompiler with highlyrobust support fortemplates, which was not common before about 2003.
Previous examples of this design approach, based on parameterized generic code, include parametric modules (functors) of theML languages,[2] and C++allocators for memory management policy.
The central idiom in policy-based design is aclass template (called thehost class), taking severaltypeparameters as input, which areinstantiated with types selected by the user (calledpolicy classes), eachimplementing a particular implicitinterface (called apolicy), andencapsulating someorthogonal (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, alibrary ormodule can support anexponential 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 tocallbacks, but differ in that, rather than consisting of a singlefunction, a policy class will typically contain several related functions (methods), often combined withstatevariables or other facilities such as nested types. A policy-based host class can be thought of as a type ofmetafunction, 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. (UnlikeMPL metafunctions, however, the output is usually represented by the instantiated host class itself, rather than a nested output type.)
A key feature of thepolicy idiom is that, usually (though it is not strictly necessary), the host class willderive from (make itself achild 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 toobject-oriented programming, policies invert the relationship betweenbase 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 incode, but rather is defined implicitly, viaduck typing, and must be documented separately and manually, incomments. 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, thetemplate method pattern can be reinterpreted for compile time, so that a main class has askeleton algorithm, which – at customization points – calls the appropriate functions of some of the policies.
This will be achieved dynamically byconcepts[3] in future versions of C++.
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 inRun and therefore the code is unable to be compiled unless both policies (Print andMessage) are provided.
#include<iostream>#include<string>template<typenameOutputPolicy,typenameLanguagePolicy>classHelloWorld:privateOutputPolicy,privateLanguagePolicy{public:// Behavior method.voidRun()const{// Two policy methods.Print(Message());}private:usingLanguagePolicy::Message;usingOutputPolicy::Print;};classOutputPolicyWriteToCout{protected:voidPrint(std::string&&message)const{std::cout<<message<<std::endl;}};classLanguagePolicyEnglish{protected:std::stringMessage()const{return"Hello, World!";}};classLanguagePolicyGerman{protected:std::stringMessage()const{return"Hallo Welt!";}};intmain(){// Example 1usingHelloWorldEnglish=HelloWorld<OutputPolicyWriteToCout,LanguagePolicyEnglish>;HelloWorldEnglishhello_world;hello_world.Run();// Prints "Hello, World!".// Example 2// Does the same, but uses another language policy.usingHelloWorldGerman=HelloWorld<OutputPolicyWriteToCout,LanguagePolicyGerman>;HelloWorldGermanhello_world2;hello_world2.Run();// Prints "Hallo Welt!".}
Designers can easily write moreOutputPolicys by adding new classes with the member functionPrint and take those as newOutputPolicys.
Loki is aC++software library written byAndrei Alexandrescu as part of his bookModern C++ Design.
The library makes extensive use of C++template metaprogramming and implements several commonly used tools:typelist,functor,singleton,smart pointer,object factory,visitor andmultimethods.
Originally the library was only compatible with two of the most standard conforming C++ compilers (CodeWarrior andComeau C/C++): later efforts have made it usable with a wide array of compilers (including olderVisual C++ 6.0,Borland C++ Builder 6.0,Clang andGCC). Compiler vendors used Loki as a compatibility benchmark, further increasing the number of compliant compilers.[4]
Maintenance and further development of Loki has been continued through an open-source community led byPeter Kümmel andRichard 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 theBoost library collection.[citation needed]