| Home | Libraries | People | FAQ | More

## Chapter 36. Boost.TypeErasure

### Steven Watanabe

Copyright © 2011-2013 Steven Watanabe

Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

## Introduction

The Boost.TypeErasure library provides runtime polymorphism in C++ that is more flexible than that provided by the core language.

C++ has two distinct kinds of polymorphism, virtual functions and templates, each of which has its own advantages and disadvantages.

- Virtual functions are not resolved until runtime, while templates are always resolved at compile time. If your types can vary at runtime (for example, if they depend on user input), then static polymorphism with templates doesn't help much.
- Virtual functions can be used with separate compilation. The body of a template has to be available in every translation unit in which it is used, slowing down compiles and increasing rebuilds.
- Virtual functions automatically make the requirements on the arguments explicit. Templates are only checked when they're instantiated, requiring extra work in testing, assertions, and documentation.
- The compiler creates a new copy of each function template every time it is instantiated. This allows better optimization, because the compiler knows everything statically, but it also causes a significant increase of binary sizes.
- Templates support Value semantics. Objects that "behave like an int" and are not shared are easier to reason about. To use virtual functions, on the other hand, you have to use (smart) pointers or references.
- Template libraries can allow third-party types to be adapted non-intrusively for seamless interoperability. With virtual functions, you have to create a wrapper that inherits from the base class.
- Templates can handle constraints involving multiple types. For example, std::for_each takes an iterator range and a function that can be called on the elements of the range. Virtual functions aren't really able to express such constraints.

The Boost.TypeErasure library combines the superior abstraction capabilities of templates, with the runtime flexibility of virtual functions.

Boost includes several special cases of this kind of polymorphism:

- `boost::any` for CopyConstructible types.
- `boost::function` for objects that can be called like functions.
- Boost.Range provides `any_iterator`.

Boost.TypeErasure generalizes this to support arbitrary requirements and provides a predefined set of common concepts

Last revised: May 05, 2016 at 21:18:10 GMT |