Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 926
Andreas Pasternak Avatar asked Oct 17 '18 14:10

Andreas Pasternak


1 Answers

There's gsl::narrow

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

like image 58
Caleth Avatar answered Oct 24 '22 05:10

Caleth