Skip to content

Commit 57c5db5

Browse files
committed
add fix suggested in #920
1 parent 2793902 commit 57c5db5

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

include/behaviortree_cpp/utils/safe_any.hpp

+28-1
Original file line numberDiff line numberDiff line change
@@ -245,7 +245,34 @@ class Any
245245
template <typename SRC, typename TO>
246246
inline bool ValidCast(const SRC& val)
247247
{
248-
return (val == static_cast<SRC>(static_cast<TO>(val)));
248+
// First check numeric limits
249+
if constexpr(std::is_arithmetic_v<SRC> && std::is_arithmetic_v<TO>)
250+
{
251+
// Handle conversion to floating point
252+
if constexpr(std::is_floating_point_v<TO>)
253+
{
254+
if constexpr(std::is_integral_v<SRC>)
255+
{
256+
// For integral to float, check if we can represent the value exactly
257+
TO as_float = static_cast<TO>(val);
258+
SRC back_conv = static_cast<SRC>(as_float);
259+
return back_conv == val;
260+
}
261+
}
262+
// Handle conversion to integral
263+
else if constexpr(std::is_integral_v<TO>)
264+
{
265+
if(val > static_cast<SRC>(std::numeric_limits<TO>::max()) ||
266+
val < static_cast<SRC>(std::numeric_limits<TO>::lowest()))
267+
{
268+
return false;
269+
}
270+
}
271+
}
272+
273+
TO as_target = static_cast<TO>(val);
274+
SRC back_to_source = static_cast<SRC>(as_target);
275+
return val == back_to_source;
249276
}
250277

251278
template <typename T>

0 commit comments

Comments
 (0)