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 writ
Sure, it's possible. Here are the ingredients. Let's start with my two favorite meta-functions:
template
struct constant
{
enum { value = N };
};
template
struct return_
{
typedef T type;
};
Then, a meta-function that counts the bits required to store a number:
template
struct bitcount : constant<1 + bitcount<(N>>1)>::value> {};
template<>
struct bitcount<0> : constant<1> {};
template<>
struct bitcount<1> : constant<1> {};
Then, a meta-function that counts the bytes:
template
struct bytecount : constant<((bitcount::value + 7) >> 3)> {};
Then, a meta-function that returns the smallest type for a given number of bytes:
template
struct bytetype : return_ {};
template<>
struct bytetype<4> : return_ {};
template<>
struct bytetype<3> : return_ {};
template<>
struct bytetype<2> : return_ {};
template<>
struct bytetype<1> : return_ {};
And finally, the meta-function that you asked for:
template
struct Integer : bytetype::value> {};