Copyright © 2001 Kevlin Henney
Copyright © 2013-2023 Antony Polukhin
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)
Table of Contents
There are times when a generic (in the sense of general as opposed to template-based programming) type is needed: variables that are truly variable, accommodating values of many other more specific types rather than C++'s normal strict and static types. We can distinguish three basic kinds of generic type:
string, and freely convert between them, for instance interpreting
"5"or vice-versa. Such types are common in scripting and other interpreted languages.
boost::lexical_castsupports such conversion functionality.
5is held strictly as an
intand is not implicitly convertible either to
5.0. Their indifference to interpretation but awareness of type effectively makes them safe, generic containers of single values, with no scope for surprises from ambiguous conversions.
void *, which offers plenty of scope for surprising, undefined behavior.
boost::any class (based on the
class of the same name described in Valued
Conversions by Kevlin Henney, C++ Report 12(7),
July/August 2000) is a variant value type based on the second category. It
supports copying of any value type and safe checked extraction of that value
strictly against its type. A similar design, offering more appropriate operators,
can be used for a generalized function adaptor,
a generalized iterator adaptor,
and other object types that need uniform runtime treatment but support only
compile-time template parameter conformance.
class (based on the utils::AnyMovable
class from the 🐙 userver framework)
is a variant value type based on the second category. It supports safe checked
extraction of that value strictly against its type and passing ownership of
the value. Think of
as of an alternative to
std::any) that does not require copy or move construction
from the held type.