gpt4 book ai didi

c++ - 自动选择一个足以容纳指定数字的变量类型

转载 作者:IT老高 更新时间:2023-10-28 13:58:12 31 4
gpt4 key购买 nike

在 C++ 中有什么方法可以定义一个足够大的类型,最多可以容纳一个特定的数字,大概是使用一些聪明的模板代码。例如我希望能够写:-

Integer<10000>::type dataItem;

并且将该类型解析为足以容纳指定值的最小类型?

背景:我需要使用来自外部数据文件的脚本生成一些变量定义。我想我可以让脚本查看这些值,然后根据值使用 uint8_tuint16_tuint32_t 等,但它将大小构建到生成的 C++ 代码中似乎更优雅

我看不到任何方法可以制作可以做到这一点的模板,但是知道 C++ 模板,我确信有办法。有什么想法吗?

最佳答案

Boost.Integer 已经为 Integer Type Selection 提供了设施。 :

boost::int_max_value_t<V>::least

The smallest, built-in, signed integral type that can hold all the values in the inclusive range 0 - V. The parameter should be a positive number.

boost::uint_value_t<V>::least

The smallest, built-in, unsigned integral type that can hold all positive values up to and including V. The parameter should be a positive number.

关于c++ - 自动选择一个足以容纳指定数字的变量类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7038797/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com