Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 8 additions & 25 deletions include/behaviortree_cpp/utils/convert_impl.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -89,41 +89,24 @@ inline void checkLowerLimit(const From& from)
template <typename From, typename To>
inline void checkTruncation(const From& from)
{
// Handle integer to floating point
if constexpr(std::is_integral_v<From> && std::is_floating_point_v<To>)
{
// Check if value can be represented exactly in the target type
To as_float = static_cast<To>(from);
From back_conv = static_cast<From>(as_float);
if(back_conv != from)
{
throw std::runtime_error("Loss of precision in conversion to floating point");
}
}
// Handle floating point to integer
if constexpr(std::is_floating_point_v<From> && std::is_integral_v<To>)
{
if(from > static_cast<From>(std::numeric_limits<To>::max()) ||
from < static_cast<From>(std::numeric_limits<To>::lowest()) ||
from != std::nearbyint(from))
if(from != std::nearbyint(from))
{
throw std::runtime_error("Invalid floating point to integer conversion");
}
}
// Handle other conversions
else

To as_target = static_cast<To>(from);
From back_to_source = static_cast<From>(as_target);
if(from != back_to_source)
{
if(from > static_cast<From>(std::numeric_limits<To>::max()) ||
from < static_cast<From>(std::numeric_limits<To>::lowest()))
{
throw std::runtime_error("Value outside numeric limits");
}
To as_target = static_cast<To>(from);
From back_to_source = static_cast<From>(as_target);
if(from != back_to_source)
if constexpr(std::is_integral_v<From> && std::is_floating_point_v<To>)
{
throw std::runtime_error("Value truncated in conversion");
throw std::runtime_error("Loss of precision in conversion to floating point");
}
throw std::runtime_error("Value truncated in conversion");
}
}

Expand Down
Loading