safe_cast.h
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032 #ifndef PLANCK_SAFE_CAST_H
00033 #define PLANCK_SAFE_CAST_H
00034
00035 #include <limits>
00036 #include "error_handling.h"
00037
00038 template<typename T1, typename T2, bool s1, bool s2> struct safe_cast_helper__
00039 {};
00040
00041 template<typename T1, typename T2> struct safe_cast_helper__ <T1,T2,true,true>
00042 {
00043 static T1 cast (const T2 &arg)
00044 {
00045 T1 res = T1(arg);
00046 planck_assert(T2(res)==arg, "safe_cast: value changed during cast");
00047 return res;
00048 }
00049 };
00050
00051 template<typename T1, typename T2> struct safe_cast_helper__ <T1,T2,false,false>
00052 {
00053 static T1 cast (const T2 &arg)
00054 {
00055 T1 res = T1(arg);
00056 planck_assert(T2(res)==arg, "safe_cast: value changed during cast");
00057 return res;
00058 }
00059 };
00060
00061 template<typename T1, typename T2> struct safe_cast_helper__ <T1,T2,true,false>
00062 {
00063 static T1 cast (const T2 &arg)
00064 {
00065 T1 res = T1(arg);
00066 planck_assert((res>=0) && (T2(res)==arg),
00067 "safe_cast: value changed during cast");
00068 return res;
00069 }
00070 };
00071
00072 template<typename T1, typename T2> struct safe_cast_helper__ <T1,T2,false,true>
00073 {
00074 static T1 cast (const T2 &arg)
00075 {
00076 T1 res = T1(arg);
00077 planck_assert((arg>=0) && (T2(res)==arg),
00078 "safe_cast: value changed during cast");
00079 return res;
00080 }
00081 };
00082
00083
00084
00085
00086 template<typename T1, typename T2> inline T1 safe_cast(const T2 &arg)
00087 {
00088 return safe_cast_helper__<T1,T2,std::numeric_limits<T1>::is_signed,
00089 std::numeric_limits<T2>::is_signed>::cast(arg);
00090 }
00091
00092 #endif