How to change the integer type used by an enum (C++)?

前端 未结 4 2023
既然无缘
既然无缘 2021-01-03 18:49

If I have an C++ enum:

enum Foo
{
  Bar,
  Baz,
  Bork,
};

How do I tell the compiler to use a uint16_t to actually store the

4条回答
  •  猫巷女王i
    2021-01-03 18:59

    With pre-C++2011 you can force a minimum storage by using a suitable range of values:

    enum foo {
        v0 = 0,
        vmax = 32767
    };
    

    I think the compiler is free to choose either a sign or an unsigned integer type as the underlying type. The above range enforced that the representation uses at least short as it underlying integer. Making it even one bigger may cause it to use long instead. Of course, this only forces a minimum range and the compiler is free to choose a bigger range. Also, with the above definition you are not allowed to stray outside the range [0, 32767]: if you really need a 16 bit range (at least) you need to use corresponding values).

提交回复
热议问题