Riko - 10 days ago 6

C++ Question

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

`typedef int32_t myType;`

typedef int16_t myTypeHalf;

Answer

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.