Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically pick a variable type big enough to hold a specified number

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?

like image 781
jcoder Avatar asked Aug 12 '11 10:08

jcoder


1 Answers

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.

like image 59
Georg Fritzsche Avatar answered Oct 25 '22 19:10

Georg Fritzsche