Riko Riko - 9 months ago 41
C++ Question

How to define a type relative to other type's size?

Is it possible to define a type in a way that it will always take a half of already defined type size?

typedef int16_t myType;
typedef int8_t myTypeHalf;

So when I decide to change myType from int16_t to int32_t, myTypeHalf would change automatically to int16_t, so I wouldn't need to worry that I might forget to change myTypeHalf.

typedef int32_t myType;
typedef int16_t myTypeHalf;

Answer Source

You can define a set of template specializations like this:

template<size_t Bits> struct SizedInt;
template<> struct SizedInt<8> { using type = std::int8_t; };    
template<> struct SizedInt<16>{ using type = std::int16_t; };
template<> struct SizedInt<32>{ using type = std::int32_t; };
template<> struct SizedInt<64>{ using type = std::int64_t; };

template<size_t Bits>
using SizedInt_t = typename SizedInt<Bits>::type;

Then you can define your types like this:

using myType = std::int32_t;
using myTypeHalf SizedInt_t<sizeof(myType) * 4>;

Of course, you can use a more complicated mathematical expression to handle special cases (like when myType is std::int8_t), but I think this gets the idea across.