自动选择大到足以容纳指定数字的变量类型 [英] Automatically pick a variable type big enough to hold a specified number

查看:145
本文介绍了自动选择大到足以容纳指定数字的变量类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  Integer< 10000> :: type dataItem; 

并且该类型是否解析为足够容纳指定值的最小类型? p>

背景:我需要使用外部数据文件中的脚本生成一些变量定义。我想我可以让脚本看看这些值,然后使用 uint8_t uint16_t uint32_t 等,这取决于值,但似乎更加优雅来构建生成的C ++代码的大小。



我看不到任何方法来做一个模板,可以做到这一点,但知道C ++模板,我敢肯定有一种方法。任何想法?

解决方案

Boost.Integer已经有整数类型选择

  boost :: int_max_value_t< V> :: minimum 




最小的,内置的有符号整数类型,可以保存所有的值在包含范围0 - V.参数应该是一个正数。




  boost :: uint_value_t< V> :: least 




最小的内置无符号整数类型,可以容纳所有正值,参数应为正数。



Is there any way in C++ define a type that is big enough to hold at most a specific number, presumably using some clever template code. For example I want to be able to write :-

Integer<10000>::type dataItem;

And have that type resolve to the smallest type that is big enough to hold the specified value?

Background: I need to generate some variable defintions using a script from an external data file. I guess I could make the script look at the values and then use uint8_t, uint16_t, uint32_t, etc. depending on the value, but it seems more elegant to build the size into the generated C++ code.

I can't see any way to make a template that can do this, but knowing C++ templates, I'm sure there is a way. Any ideas?

解决方案

Boost.Integer already has facilities for 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.

这篇关于自动选择大到足以容纳指定数字的变量类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆