是否可以以一种始终占用已定义类型大小的一半的方式定义类型?
typedef int16_t myType;
typedef int8_t myTypeHalf;
Run Code Online (Sandbox Code Playgroud)
所以,当我决定改变的myType从int16_t到int32_t,myTypeHalf会自动更改为int16_t,所以我就不需要担心,我会忘记更改myTypeHalf.
typedef int32_t myType;
typedef int16_t myTypeHalf;
Run Code Online (Sandbox Code Playgroud)
您可以定义一组模板特化,如下所示:
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;
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样定义你的类型:
using myType = std::int32_t;
using myTypeHalf = SizedInt_t<sizeof(myType) * 4>;
Run Code Online (Sandbox Code Playgroud)
当然,你可以使用更复杂的数学表达式来处理特殊情况(比如当myType是std::int8_t),但我认为这一点对有想法.