Search code examples
c++c++11type-safetynarrowing

Is there a "safe" static_cast alternative?


Is there a "safe" alternative to static_cast in C++11/14 or a library which implements this functionality?

By "safe" I mean the cast should only allow casts which do not lose precision. So a cast from int64_t to int32_t would only be allowed if the number fits into a int32_t and else an error is reported.


Solution

  • There's gsl::narrow

    narrow // narrow<T>(x) is static_cast<T>(x) if static_cast<T>(x) == x or it throws narrowing_error