Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

Building More Flexible Types with Mixins


January, 2006: Building More Flexible Types With Mixins

Christopher Diggins is a freelance consultant and developer of the Heron programming language. He is a coauthor of the C++ Cookbook (O'Reilly, 2005) and can be reached at http://www.cdiggins.com/.


In C++, the Curiously Recurring Template Pattern (CRTP) [1] is a common name given to the technique of inheriting from a template parameter. Outside of the C++ community, this technique is known more widely as a mixin [2]. Mixins are described in the literature to be a powerful tool for expressing abstractions, but CRTP is often viewed as a somewhat exotic technique, and somewhat under utilized. In this article, I plan on showing how it can be used in a rather pedestrian manner to create simple designs that are significantly more flexible.

What many programmers realize, through observing Java and other languages, is that hierarchical layers of abstraction in our designs can reduce the amount of code we have to write and maintain. Furthermore, they can isolate the ripple effect of changes when refactoring, making such designs more appropriate for agile development.

Unfortunately, traditional OOP techniques for expressing abstractions, such as using abstract base classes, are not often used in C++ code. One of the big reasons for this is that it is incompatible with generic programming techniques such as those used by the STL. However, the advantages of OO designs can be achieved, even in generic designs, by using mixin-based composition of classes through simple application of the CRTP pattern.

Let's start by looking at a simple example, my favorite abstract data type (ADT), the stack. A stack ADT can be expressed minimally in C++ as an abstract base class (ABC), as shown in Listing 1.

A very trivial, yet effective, implementation of the AbstractStack is shown in Listing 2.

In and of itself, the ConcreteStack is not particularly useful in any real-world scenario because it is severely lacking in functionality. It could be augmented easily through the introduction of several utility functions such as: PushCopy(), MultiPop(), Clear(), Duplicate(), Exchange(), Top(), Reverse(), and so on. These functions can be added directly to ConcreteStack, but if I do that, what happens if I need a new implementation of AbstractStack? Consider the perfectly reasonable alternative implementation of FixedStack, which inherits AbstractStack in Listing 3.

All of the utility functions would have to be more or less cut and pasted into this new implementation. This violates a principle rule of programming: reduce redundancy. The obvious object-oriented solution, then, is to place the extra member functions directly in AbstractStack itself, or better yet, in a separate class that inherits from AbstractStack, such as AbstractStackExtension in Listing 4.

The approach of extending ADTs in this manner is very useful until you try to apply it to a container designed using generic-programming techniques, and wish to extend a concept in a similar manner. Consider the IterableConcept (expressed in pseudocode) in Listing 5.

You can't express a concept as an abstract type because the dependent member types (e.g., Iterator) are specific to (dependent on) the concrete implementation. This doesn't mean you can't still express an extension as a separate abstraction.

Let's say you want to introduce a set of utility member functions, ForEach(), IsEmpty(), and Count(), which can be used with any class that models a particular concept. Using the CRTP, this can be done as a separate layer of abstraction, for instance in Listing 6.

In order to use the extension class in conjunction with a class that models the concept being extended, you need to create a third class that glues the extension class to the implementation class through inheritance. This is demonstrated in Listing 7.

The biggest drawback of the CRTP technique is that constructors aren't inherited. This means that if you use an initializing constructor in your implementation class, every extension will have to have an appropriate initializing constructor. This causes the extensions to be more restricted and, as such, less useful.

Clearly, the CRTP is a very expressive technique. Furthermore, it is more efficient than the more traditional OO approach because there is no abstraction penalty paid. Now we just have to wait and see if C++ will enable constructor initialization in the future.

Acknowledgments

Much thanks to Max Lybbert for reviewing and commenting on this article.

References

  1. Coplien, J. "Curiously Recurring Template Patterns," C++ Report, February 1995, pp. 24-27.
  2. Yannis Smaragdakis and Don Batory. Mixin-Based Programming in C++, 2000; http://citeseer.ist.psu.edu/smaragdakis00mixinbased.html.

CUJ


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.