Skip to content

Commit

Permalink
add fix suggested in #920
Browse files Browse the repository at this point in the history
  • Loading branch information
facontidavide committed Feb 9, 2025
1 parent 2793902 commit 57c5db5
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 additions & 1 deletion include/behaviortree_cpp/utils/safe_any.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,34 @@ class Any
template <typename SRC, typename TO>
inline bool ValidCast(const SRC& val)
{
return (val == static_cast<SRC>(static_cast<TO>(val)));
// First check numeric limits
if constexpr(std::is_arithmetic_v<SRC> && std::is_arithmetic_v<TO>)
{
// Handle conversion to floating point
if constexpr(std::is_floating_point_v<TO>)
{
if constexpr(std::is_integral_v<SRC>)
{
// For integral to float, check if we can represent the value exactly
TO as_float = static_cast<TO>(val);
SRC back_conv = static_cast<SRC>(as_float);
return back_conv == val;
}
}
// Handle conversion to integral
else if constexpr(std::is_integral_v<TO>)
{
if(val > static_cast<SRC>(std::numeric_limits<TO>::max()) ||
val < static_cast<SRC>(std::numeric_limits<TO>::lowest()))
{
return false;
}
}
}

TO as_target = static_cast<TO>(val);
SRC back_to_source = static_cast<SRC>(as_target);
return val == back_to_source;
}

template <typename T>
Expand Down

0 comments on commit 57c5db5

Please sign in to comment.