C++ Boost

boost::variant

Overview



Introduction

The variant class template offers a simple, type-safe solution for manipulating values from a heterogeneous set of  types in a uniform manner. Whereas standard containers such as std::vector may be thought of as "multi-value, single type," a variant is "multi-type, single value." This reduces code duplication and enhances maintainability.

Specific features of boost::variant include:


Motivation

Many times, during the development of a C++ program, the programmer finds himself in need of manipulating several distinct types in a uniform manner. Indeed, C++ features direct language support for such types through its union keyword:

union { int i; double d; } u;
u.d = 3.14;
u.i = 3; // overwrites u.d (OK: u.d is a POD type)

C++'s union construct, however, is nearly useless in an object-oriented environment. The construct entered the language primarily as a means for preserving compatibility with C, which supports only POD types, and so does not accept types exhibiting non-trivial construction or destruction:

union {
  int i;
  std::string s; // illegal: std::string is not a POD type!
};

Clearly another approach is required. Typical solutions feature the dynamic-allocation of objects, which are subsequently manipulated through a common base type (often a virtual base class [Hen01] or, more dangerously, a void*). Objects of concrete type may be then retrieved by way of a polymorphic downcast construct (e.g., dynamic_cast).

However, solutions of this sort are highly error-prone, due to the following:

Furthermore, even when properly implemented, these solutions incur a relatively significant abstraction penalty due to the use of the free store, virtual function calls, and polymorphic downcasts.

The variant template class (inspired by Andrei Alexandrescu's class of the same name described in [Ale02]) is an efficient, recursive-capable, bounded discriminated union value type capable of containing both POD and non-POD value types. It supports direct initialization from any type convertible to one of its bounded types or from a source variant whose bounded types are each convertible to one of the destination variant's bounded types. As well, variant supports both compile-time checked, type-safe visitation and explicit, run-time checked, type-safe value extraction.


Revised 13 February 2003

© Copyright Eric Friedman and Itay Maman 2002-2003. All rights reserved.

Permission to use, copy, modify, distribute and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. Eric Friedman and Itay Maman make no representations about the suitability of this software for any purpose. It is provided "as is" without express or implied warranty.