Tutorial

Basic Usage

A discriminated union container on some set of types is defined by
instantiating the boost::variant class
template with the desired types. These types are called
bounded types and are subject to the
requirements of the
BoundedType
concept. Any number of bounded types may be specified, up to some
implementation-defined limit (see
BOOST_VARIANT_LIMIT_TYPES).

For example, the following declares a discriminated union container on
int and std::string:

By default, a variant default-constructs its first
bounded type, so v initially contains int(0). If
this is not desired, or if the first bounded type is not
default-constructible, a variant can be constructed
directly from any value convertible to one of its bounded types. Similarly,
a variant can be assigned any value convertible to one of its
bounded types, as demonstrated in the following:

v = "hello";

Now v contains a std::string equal to
"hello". We can demonstrate this by
streamingv to standard
output:

std::cout << v << std::endl;

Usually though, we would like to do more with the content of a
variant than streaming. Thus, we need some way to access the
contained value. There are two ways to accomplish this:
apply_visitor, which is safest
and very powerful, and
get<T>, which is
sometimes more convenient to use.

For instance, suppose we wanted to concatenate to the string contained
in v. With value retrieval
by get, this may be accomplished
quite simply, as seen in the following:

As desired, the std::string contained by v now
is equal to "hello world! ". Again, we can demonstrate this by
streaming v to standard output:

std::cout << v << std::endl;

While use of get is perfectly acceptable in this trivial
example, get generally suffers from several significant
shortcomings. For instance, if we were to write a function accepting a
variant<int, std::string>, we would not know whether
the passed variant contained an int or a
std::string. If we insisted upon continued use of
get, we would need to query the variant for its
contained type. The following function, which "doubles" the
content of the given variant, demonstrates this approach:

However, such code is quite brittle, and without careful attention will
likely lead to the introduction of subtle logical errors detectable only at
runtime. For instance, consider if we wished to extend
times_two to operate on a variant with additional
bounded types. Specifically, let's add
std::complex<double> to the set. Clearly, we would need
to at least change the function declaration:

Of course, additional changes are required, for currently if the passed
variant in fact contained a std::complex value,
times_two would silently return -- without any of the desired
side-effects and without any error. In this case, the fix is obvious. But in
more complicated programs, it could take considerable time to identify and
locate the error in the first place.

Thus, real-world use of variant typically demands an access
mechanism more robust than get. For this reason,
variant supports compile-time checked
visitation via
apply_visitor. Visitation requires
that the programmer explicitly handle (or ignore) each bounded type. Failure
to do so results in a compile-time error.

Visitation of a variant requires a visitor object. The
following demonstrates one such implementation of a visitor implementating
behavior identical to times_two:

As expected, the content of v is now a
std::string equal to "hello world! hello world! ".
(We'll skip the verification this time.)

In addition to enhanced robustness, visitation provides another
important advantage over get: the ability to write generic
visitors. For instance, the following visitor will "double" the
content of anyvariant (provided its
bounded types each support operator+=):

While the initial setup costs of visitation may exceed that required for
get, the benefits quickly become significant. Before concluding
this section, we should explore one last benefit of visitation with
apply_visitor:
delayed visitation. Namely, a special form
of apply_visitor is available that does not immediately apply
the given visitor to any variant but rather returns a function
object that operates on any variant given to it. This behavior
is particularly useful when operating on sequences of variant
type, as the following demonstrates:

Advanced Topics

This section discusses several features of the library often required
for advanced uses of variant. Unlike in the above section, each
feature presented below is largely independent of the others. Accordingly,
this section is not necessarily intended to be read linearly or in its
entirety.

Preprocessor macros

While the variant class template's variadic parameter
list greatly simplifies use for specific instantiations of the template,
it significantly complicates use for generic instantiations. For instance,
while it is immediately clear how one might write a function accepting a
specific variant instantiation, say
variant<int, std::string>, it is less clear how one
might write a function accepting any given variant.

Due to the lack of support for true variadic template parameter lists
in the C++98 standard, the preprocessor is needed. While the
Preprocessor library provides a general and
powerful solution, the need to repeat
BOOST_VARIANT_LIMIT_TYPES
unnecessarily clutters otherwise simple code. Therefore, for common
use-cases, this library provides its own macro
BOOST_VARIANT_ENUM_PARAMS.

This macro simplifies for the user the process of declaring
variant types in function templates or explicit partial
specializations of class templates, as shown in the following:

Using a type sequence to specify bounded types

While convenient for typical uses, the variant class
template's variadic template parameter list is limiting in two significant
dimensions. First, due to the lack of support for true variadic template
parameter lists in C++, the number of parameters must be limited to some
implementation-defined maximum (namely,
BOOST_VARIANT_LIMIT_TYPES).
Second, the nature of parameter lists in general makes compile-time
manipulation of the lists excessively difficult.

To solve these problems,
make_variant_over< Sequence >
exposes a variant whose bounded types are the elements of
Sequence (where Sequence is any type fulfilling
the requirements of MPL's
Sequence concept). For instance,

Portability: Unfortunately, due to
standard conformance issues in several compilers,
make_variant_over is not universally available. On these
compilers the library indicates its lack of support for the syntax via the
definition of the preprocessor symbol
BOOST_VARIANT_NO_TYPE_SEQUENCE_SUPPORT.

Recursive variant types

Recursive types facilitate the construction of complex semantics from
simple syntax. For instance, nearly every programmer is familiar with the
canonical definition of a linked list implementation, whose simple
definition allows sequences of unlimited length:

template <typename T>
struct list_node
{
T data;
list_node * next;
};

The nature of variant as a generic class template
unfortunately precludes the straightforward construction of recursive
variant types. Consider the following attempt to construct
a structure for simple mathematical expressions:

While well-intentioned, the above approach will not compile because
binary_op is still incomplete when the variant
type expression is instantiated. Further, the approach suffers
from a more significant logical flaw: even if C++ syntax were different
such that the above example could be made to "work,"
expression would need to be of infinite size, which is
clearly impossible.

Because variant provides special support for
recursive_wrapper, clients may treat the resultant
variant as though the wrapper were not present. This is seen
in the implementation of the following visitor, which calculates the value
of an expression without any reference to
recursive_wrapper:

Binary visitation

As the tutorial above demonstrates, visitation is a powerful mechanism
for manipulating variant content. Binary visitation further
extends the power and flexibility of visitation by allowing simultaneous
visitation of the content of two different variant
objects.

Notably this feature requires that binary visitors are incompatible
with the visitor objects discussed in the tutorial above, as they must
operate on two arguments. The following demonstrates the implementation of
a binary visitor: