feat: Implementation of Safe Type Conversion Templates in C++ #1951
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Objective
This Pull Request introduces a series of C++ templates designed to facilitate safe and efficient type conversions. The aim is to replace explicit
static_cast
calls in the existing codebase, enhancing both the safety and readability of the code.Key Changes
get_default_value<T>()
: Provides default values for typeT
, distinguishing between arithmetic and non-arithmetic types.number_to_string<U>(value)
: Efficiently converts numerical values to strings usingstd::to_chars
, applicable to both integral and floating-point types.safe_convert<T, U>(value, callerName, defaultValue)
: Ensures safe type conversions, incorporating checks for overflow, underflow, precision loss, and non-finite floating-point values. Specialized for various type combinations, including conversions fromenum
to arithmetic types, and fromstring
to numeric types.Benefits
static_cast
instances with more expressive and intentional function calls.Usage Examples
Examples illustrating the practical application of each template are included in "src/utils/safe_convert.hpp", demonstrating their utility across diverse type conversion situations.
Notes