Riko
Riko

Reputation: 453

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;

Upvotes: 2

Views: 99

Answers (2)

Benjamin Lindley
Benjamin Lindley

Reputation: 103751

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.

Upvotes: 7

Kirill Kobelev
Kirill Kobelev

Reputation: 10557

Try something like:

template<typename T>
struct HalfType
{
    typedef int8_t Type;
};

and a bunch of specializations, like:

template<>
struct HalfType<int32_t>
{
    typedef int16_t Type;
};

..............

The number of possible cases is not that big. You can simply specify them all. Once there is no hallf type for the type passed, the default template will give out int8_t. The use should look like

HalfType<somePassedType>::Type myVarOfHalfTheSize;

Upvotes: 2

Related Questions