@@ -89,41 +89,24 @@ inline void checkLowerLimit(const From& from)
8989template <typename From, typename To>
9090inline void checkTruncation (const From& from)
9191{
92- // Handle integer to floating point
93- if constexpr (std::is_integral_v<From> && std::is_floating_point_v<To>)
94- {
95- // Check if value can be represented exactly in the target type
96- To as_float = static_cast <To>(from);
97- From back_conv = static_cast <From>(as_float);
98- if (back_conv != from)
99- {
100- throw std::runtime_error (" Loss of precision in conversion to floating point" );
101- }
102- }
10392 // Handle floating point to integer
10493 if constexpr (std::is_floating_point_v<From> && std::is_integral_v<To>)
10594 {
106- if (from > static_cast <From>(std::numeric_limits<To>::max ()) ||
107- from < static_cast <From>(std::numeric_limits<To>::lowest ()) ||
108- from != std::nearbyint (from))
95+ if (from != std::nearbyint (from))
10996 {
11097 throw std::runtime_error (" Invalid floating point to integer conversion" );
11198 }
11299 }
113- // Handle other conversions
114- else
100+
101+ To as_target = static_cast <To>(from);
102+ From back_to_source = static_cast <From>(as_target);
103+ if (from != back_to_source)
115104 {
116- if (from > static_cast <From>(std::numeric_limits<To>::max ()) ||
117- from < static_cast <From>(std::numeric_limits<To>::lowest ()))
118- {
119- throw std::runtime_error (" Value outside numeric limits" );
120- }
121- To as_target = static_cast <To>(from);
122- From back_to_source = static_cast <From>(as_target);
123- if (from != back_to_source)
105+ if constexpr (std::is_integral_v<From> && std::is_floating_point_v<To>)
124106 {
125- throw std::runtime_error (" Value truncated in conversion" );
107+ throw std::runtime_error (" Loss of precision in conversion to floating point " );
126108 }
109+ throw std::runtime_error (" Value truncated in conversion" );
127110 }
128111}
129112
0 commit comments