Skip to content

Commit fc80e7f

Browse files
committed
Reject floating point narrowing, further to #106
1 parent 75c7b9a commit fc80e7f

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

include/cpp2util.h

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -739,6 +739,20 @@ inline constexpr auto as() -> auto
739739
}
740740
}
741741

742+
template< typename C >
743+
inline constexpr auto as(auto const& x) -> auto
744+
requires (
745+
std::is_floating_point_v<C> &&
746+
std::is_floating_point_v<CPP2_TYPEOF(x)> &&
747+
sizeof(CPP2_TYPEOF(x)) > sizeof(C)
748+
)
749+
{
750+
static_assert(
751+
program_violates_type_safety_guarantee<C, CPP2_TYPEOF(x)>,
752+
"No safe 'as' cast from larger to smaller floating point precision - if you're sure you want this unsafe conversion, consider using `unsafe_narrow<T>()` to force the conversion"
753+
);
754+
}
755+
742756
// Signed/unsigned conversions to a not-smaller type are handled as a precondition,
743757
// and trying to cast from a value that is in the half of the value space that isn't
744758
// representable in the target type C is flagged as a Type safety contract violation

0 commit comments

Comments
 (0)