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
TandFsatisfyCast<T, F>, it means thatFcan be cast toTthrough 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 extendFin order to do the conversion toT. -
Default types are able to be constructed with a default value.
-
A concept that indicates
ToTypecan be constructed from aFromType, viaToType::from(FromType). -
A concept that declares
FromTypecan be converted toToType. -
Returns whether a type
Fromis safely constructible from a reference of typeTo. IfTois a const reference, then the types must match, as a conversion would create a reference to a temporary. -
A concept that indicates
ToTypecan be (sometimes) constructed from aFromType, viaToType::try_from(FromType). -
A concept that declares
FromTypecan (sometimes) be converted toToTypethrough theTryFromconcept or through an identity transformation.