Reputation: 16747
If I have compile time constant num_bits
how can I get smallest integer type that can hold this amount of bits?
Of course I can do:
#include <cstdint>
#include <type_traits>
std::size_t constexpr num_bits = 19;
using T =
std::conditional_t<num_bits <= 8, uint8_t,
std::conditional_t<num_bits <= 16, uint16_t,
std::conditional_t<num_bits <= 32, uint32_t,
std::conditional_t<num_bits <= 64, uint64_t,
void>>>>;
But maybe there exists some ready made meta function in standard library for achieving this goal?
I created this question only to find out single meta function specifically from standard library. But if you have other nice suggestions how to solve this task besides my proposed above solution, then please post such solutions too...
Update. As suggested in comments, uint_leastX_t
should be used instead of uintX_t
everywhere in my code above, as uintX_t
may not exist on some platforms, while uint_leastX_t
always exist.
Upvotes: 5
Views: 1744
Reputation: 51040
There is currently no template type for this in the c++ standard library.
The standard library does have something to do the reverse of what you're looking for (std::numeric_limits<T>::max
).
There is a proposal to add such functionality to the c++ standard library in p0102: "C++ Parametric Number Type Aliases". A similar question to yours has been asked on lists.isocpp.org/std-proposals, where p0102 was mentioned.
In case you're interested in / okay with using Boost, Boost has boost::int_max_value_t<V>
, which is a struct defining type members least
(smallest) and fast
("easiest to manipulate").
Upvotes: 1