/* * This file is part of libgim. * * libgim is free software: you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * libgim is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with libgim. If not, see . * * Copyright 2011 Danny Robson */ #ifndef __UTIL_TYPES_CASTS_HPP #define __UTIL_TYPES_CASTS_HPP #include "../debug.hpp" #include #include //----------------------------------------------------------------------------- namespace detail { template T _sign_cast (const typename std::enable_if::value && std::is_signed::value, V>::type v) { CHECK_GE (v, 0); return static_cast (v); } template T _sign_cast (const typename std::enable_if::value && std::is_unsigned::value, V>::type v) { CHECK_LT (v, std::numeric_limits::max () / 2); return static_cast (v); } template T _sign_cast (const typename std::enable_if::value, V>::type v) { return v; } } /// Safely cast a numeric type to its (un)signed counterpart, aborting if the /// dynamically checked result is not representable. May be optimised out if /// NDEBUG is defined. template T sign_cast (const V v) { return detail::_sign_cast(v); } ///---------------------------------------------------------------------------- /// assert if the value cannot be cast loslessly from U to T, else return the /// converted value.Note: this is only a debug-time check and is compiled out /// in optimised builds. template T trunc_cast (U u) { auto t = static_cast (u); if (u == u) CHECK_EQ (t, u); else CHECK_NEQ (t, t); return t; } ///---------------------------------------------------------------------------- /// assert if the value is not a pointer to a subclass of T, else return the /// converted value. Note: this is only a debug-time check and is compiled out /// in optimised builds. template T* known_cast (V *v) { CHECK (dynamic_cast (v)); return static_cast (v); } //----------------------------------------------------------------------------- template T& known_cast (V &v) { CHECK_NOTHROW (dynamic_cast (v)); return static_cast (v); } #endif