KNarrow Namespace
Narrowing conversion utilities. More...
| Header: | #include <KNarrow> |
| CMake: | find_package(KF6 REQUIRED COMPONENTS CoreAddons)target_link_libraries(mytarget PRIVATE KF6::CoreAddons) |
| Since: | 6.33 |
Classes
| struct | NarrowingError |
Types
| enum class | NarrowingErrorType { ValueChanged, ValueMeaningChanged } |
Functions
| int | expectingNarrow(Input i) |
| Output | narrow(Input i) |
Detailed Description
This namespace provides utilities for performing narrowing conversions safely. If you have C++23 enabled, which is recommended, then you can use expectingNarrow. If you do not have C++23 or want to abort you can use narrow.
// C++23
{
auto u = KNarrow::expectingNarrow<unsigned int>(30); // OK, a value of 30 fits in an unsigned
if (u.has_value()) {
// Use the value
}
auto i = KNarrow::expectingNarrow<int>(std::numeric_limits<long>::max()); // Bad, a value of long::max does not fit in an int
if (i.has_value()) {
// Use the value. It won't have one though :)
}
}
// Always available
{
auto u = KNarrow::narrow<unsigned int>(30); // OK
auto i = KNarrow::narrow<int>(std::numeric_limits<long>::max()); // aborts or throws
}
Type Documentation
enum class KNarrow::NarrowingErrorType
Types of narrowing errors
| Constant | Value | Description |
|---|---|---|
KNarrow::NarrowingErrorType::ValueChanged | 0 | The value changed during narrowing (e.g. uint64::max to uint32 would yield different values) |
KNarrow::NarrowingErrorType::ValueMeaningChanged | 1 | The value technically is the same but its domain meaning has changed (e.g. uint8::max to int8 would be the same value in their respective domains but means different things: 255 versus -1 depending on which representation you compare with) |
Function Documentation
template <typename Output, typename Input> int KNarrow::expectingNarrow(Input i)
Narrow Input into Output type and return a std::expected. Similar to gsl::narrow().
i The input value to narrow
Returns The narrowed value of type Output. When the value is not compatible with the target type a std::unexpected containing the KNarrow::NarrowingErrorType is returned.
Note: This function requires C++23 support for std::expected.
Warning: The documentation may incorrectly render the return type as int. It is in fact std::expected<Output, NarrowingErrorType>
template <typename Output, typename Input> Output KNarrow::narrow(Input i)
Narrow Input into Output type and abort if the value changed. Similar to gsl::narrow().
i The input value to narrow
Returns The narrowed value of type Output. When the value is not compatible with the target type an exception is thrown (if enabled), or the program aborts.