Concepts and functions for constructing and converting between types.
Type conversions
This namespace provides tools for three general methods of converting between types:
- Infallible conversions which preserve values:
From
/Into
- Fallible conversions which preserve values or fail explicitly:
TryFrom
/TryInto
- Infallib;e conversions which can change values or lose data:
Cast
Usually prefer to convert between types with the value-preserving methods
of From
and
Into
and TryInto
when possible. Cast
is required for converting
from floating point to integer values, and from larger integer types to
floating point, as these are lossy conversions.
The into
function allows explicit conversion
while deducing the target type, such as for converting function arguments
or return values.
Concept | Usage | Infallible | Preserves values |
---|---|---|---|
From / Into |
T::from(x) / sus::into(x) |
✅ | ✅ |
TryFrom / TryInto |
T::try_from(x) / sus::try_into<T>(x) |
❌ | ✅ |
Cast |
sus::cast<T>(x) |
✅ | ❌ |
See Cast
for how numeric and
primitive values are converted with cast
.
Default construction
The Default
concept matches types which can be
default constructed, allowing their use in generic code.
Constructing from and holding references
The SafelyConstructibleFromReference
concept pairs with the
[[clang::lifetimebound]]
attribute, which gives better protection with
Clang. The concept can be used in generic code that accepts reference types
to prevent receiving references to implicit temporary objects in a
standard way.
Functions
-
An infallible conversion (cast) that may lose the original value in the process.
-
Converts from the given value to whatever a receiver requires.
-
Moves from and converts from the given value to whatever a receiver requires.
-
Attempts to convert from the given value to a
ToType
.
Concepts
-
When a pair of types
T
andF
satisfyCast<T, F>
, it means thatF
can be cast toT
through a conversion that will always succeed in producing some value, but may be lossy or produce a value with a different meaning. The conversion may truncate or extendF
in order to do the conversion toT
. -
Default types are able to be constructed with a default value.
-
A concept that indicates
ToType
can be constructed from aFromType
, viaToType::from(FromType)
. -
A concept that declares
FromType
can be converted toToType
. -
Returns whether a type
From
is safely constructible from a reference of typeTo
. IfTo
is a const reference, then the types must match, as a conversion would create a reference to a temporary. -
A concept that indicates
ToType
can be (sometimes) constructed from aFromType
, viaToType::try_from(FromType)
. -
A concept that declares
FromType
can (sometimes) be converted toToType
through theTryFrom
concept or through an identity transformation.