Is there a "safe" static_cast alternative?
There's gsl::narrow
narrow //
narrow<T>(x)
isstatic_cast<T>(x)
ifstatic_cast<T>(x) == x
or it throwsnarrowing_error
You've got the use-case reversed.
The intended use of static_cast
(and the other c++-style casts) is to indicate programmer intentions. When you write auto value = static_cast<int32_t>(value_64);
, you're saying "Yes, I very much *intend* to downcast this value, possibly truncating it, when I perform this assignment". As a result, a compiler, which might have been inclined to complain about this conversion under normal circumstances (like if you'd have written int32_t value = value_64;
) instead observes "well, the programmer has told me that this is what they intended; why would they lie to me?" and will silently compile the code.
If you want your C++ code to warn or throw an error on unsafe conversions, you need to explicitly not use static_cast
, const_cast
, reinterpret_cast
, and let the compiler do its job. Compilers have flags that change how warnings are treated (downcasting int64_t
to int32_t
usually only results in a Warning), so make sure you're using the correct flags to force warnings to be treated as errors.