繁体   English   中英

如何使用模板实现 function 安全地将任何较大的类型转换为 C++ 中的较小类型?

[英]How to implement a function that safely cast any larger type to a smaller type in C++ using templates?

我正在尝试编写一个 function 来检查被转换的变量是否适合目标类型,如果不适合则 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);
}

好吧,如果这实际上是一些 function 已经这样做了,我不知道我会很高兴听到。

C++ 核心指南已经有一个gsl::narrow

//narrow():narrow_cast() 的检查版本,如果强制转换改变了值,则抛出

您可以在此处查看 Microsoft 实施

// 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 帖子上看到实现的解释(它适用于旧版本的实现,但没有发生实质性变化,因此答案仍然适用)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM