Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

types

typedef

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;
like image 997
Riko Avatar asked Dec 01 '25 09:12

Riko


2 Answers

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.

like image 159
Benjamin Lindley Avatar answered Dec 04 '25 01:12

Benjamin Lindley


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;
like image 36
Kirill Kobelev Avatar answered Dec 03 '25 23:12

Kirill Kobelev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!