问题描述
我正在尝试编写一个函数来检查被强制转换的变量是否适合目标类型,如果不适合,则使用 assert()。现在这就是我想出的。我还没有测试它。我想让模板找出自动传递的变量的类型,使用 typeid 之类的东西,尽管我真的不知道 typeid 到底是什么。那可能吗?另外,我对模板知之甚少。
template<typename from_T,typename to_T>
static inline to_T safe_cast(from_T variable)
{
assert(variable >= std::numeric_limits<to_T>::min());
assert(variable <= std::numeric_limits<to_T>::max());
return static_cast<to_T>(variable);
}
好吧,如果这实际上是一些我不知道的功能已经做到了这一点,我会很高兴听到的。
解决方法
C++ Core Guidelines 已经有一个 gsl::narrow
//窄() : 一个检查版本的narrow_cast(),如果转换改变了值就会抛出
您可以看到 Microsoft 实现 here
// narrow() : a checked version of narrow_cast() that throws if the cast changed the value
template <class T,class U>
constexpr T narrow(U u) noexcept(false)
{
constexpr const bool is_different_signedness =
(std::is_signed<T>::value != std::is_signed<U>::value);
const T t = narrow_cast<T>(u);
if (static_cast<U>(t) != u || (is_different_signedness && ((t < T{}) != (u < U{}))))
{
throw narrowing_error{};
}
return t;
}
您可以查看实现 on this SO post 的说明(它适用于较旧版本的实现,但没有实质性更改,因此答案仍然适用)。