在C ++核心原则有一个narrow抛出如果转换改变了值施放。查看该库的microsoft实现:
// narrow() : a checked version of narrow_cast() that throws if the cast changed the value
template <class T, class U>
T narrow(U u) noexcept(false)
{
T t = narrow_cast<T>(u);
if (static_cast<U>(t) != u)
gsl::details::throw_exception(narrowing_error());
if (!details::is_same_signedness<T, U>::value && ((t < T{}) != (u < U{}))) // <-- ???
gsl::details::throw_exception(narrowing_error());
return t;
}
Run Code Online (Sandbox Code Playgroud)
我不明白第二个if。它会检查什么特殊情况static_cast<U>(t) != u?为什么还不够?
为了完整性:
narrow_cast只是一个static_cast:
// narrow_cast(): a searchable way to do …Run Code Online (Sandbox Code Playgroud)