casting - C++ typecast double -


is there way in c++ typecast double float, int32, uint8 or bool without loosing information? , if not possible return error?

edit: not clear enough...

i have function gets parameters double , type. function should check whether can typecast double type without loosing information.

bool check_type(double value, enumtype type) {     switch(type) {         case enum_uint8:             return "check wheter value can typecasted type"             break;         case enum_float:              .              .              .     }     return false; } 

maybe try this:

#include <limits>  template<typename t> inline bool is_in_allowed_range(double value) {     return (         (value >= static_cast<double>(std::numeric_limits<t>::min())) &&         (value <= static_cast<double>(std::numeric_limits<t>::max()))     ); }  bool check_type(double value, enumtype type) {     switch(type) {         case enum_uint8:             return is_in_allowed_range<uint8>(value);         case enum_float:             return is_in_allowed_range<float>(value);         ...     }     return false; }  ...  double value = ...; if (check_type(value, enum_uint8)) {     uint u = static_cast<uint8>(value);     // use u needed ... } 

or simpler:

#include <limits>  template<typename t> bool convert_to_type(double value, t *arg) {     if ((value >= static_cast<double>(std::numeric_limits<t>::min())) &&         (value <= static_cast<double>(std::numeric_limits<t>::max())))     {         *arg = static_cast<t>(value);         return true;     }     return false; }  ...  double value = ...; uint8 u; if (convert_to_type(value, &u)) {     // use u needed... } 

Comments