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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With