我试图写一个函数,检查被转换的变量是否适合目标类型,如果不适合,则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++核心指南已经有了gsl::narrow
//narrow(): narrow()的检查版本,如果强制转换改变了
的值,则抛出
你可以在这里看到微软的实现
// 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; }
你可以在这个SO帖子上看到对实现的解释(这是一个旧版本的实现,但没有实质性的改变,所以答案仍然适用)。