Home | Libraries | People | FAQ | More |
Copyright © 2001 Kevlin Henney
Copyright © 2013-2024 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:
int
and string
, and freely convert between them,
for instance interpreting 5
as "5"
or vice-versa.
Such types are common in scripting and other interpreted languages. boost::lexical_cast
supports such conversion
functionality.
5
is held strictly as an int
and is not implicitly convertible either to "5"
or 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.
The 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, any_function
,
a generalized iterator adaptor, any_iterator
,
and other object types that need uniform runtime treatment but support only
compile-time template parameter conformance.
The boost::anys::unique_any
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 boost::anys::unique_any
as of an alternative to boost::any
(or to std::any
) that does not require copy or move construction
from the held type.