From 4891c6af0e964bdbaf549bc2c7bd038ccee1bb73 Mon Sep 17 00:00:00 2001 From: Danny Robson Date: Wed, 15 Jun 2011 22:38:58 +1000 Subject: [PATCH] Add sign_cast functions These safely cast between signed and unsigned numeric quantities, aborting if the result cannot be safely converted (as opposed to size expanding or throwing). --- types.hpp | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/types.hpp b/types.hpp index f101a529..afee0e5a 100644 --- a/types.hpp +++ b/types.hpp @@ -3,6 +3,7 @@ #include #include +#include template struct bits_type; @@ -53,4 +54,43 @@ template std::string type_to_string (void); +template +struct sign_types; + + +template <> struct sign_types { + typedef signed int with_sign; + typedef unsigned int without_sign; +}; + + +template <> struct sign_types { + typedef signed int with_sign; + typedef unsigned int without_sign; +}; + + +/// Safely cast a numeric type to its signed comparison, aborting if the +/// result is not representable. +template +typename sign_types::with_sign +sign_cast (const typename sign_types::without_sign v) +{ + check_hard (v <= std::numeric_limits::without_sign>::max () >> 1); + return static_cast ::with_sign> (v); +} + + +/// Safely cast a numeric type to its unsigned comparison, aborting if the +/// result is not representable. +template +typename sign_types::without_sign +sign_cast (const typename sign_types::with_sign v) +{ + check_hard (v >= 0); + return static_cast ::without_sign> (v); +} + + + #endif // __TYPES_HPP