Home > Software engineering >  How to define an enum template (C 20)?
How to define an enum template (C 20)?

Time:07-09

enum ByteOrder :uint16_t
{
    LittleEndian = 0x4949,
    BigEndian = 0x4D4D,
};
template<ByteOrder BO>
enum SF :uint16_t;
template<>
enum SF<LittleEndian>
{
    SF_A = 0x0001;
};
template<>
enum SF<BigEndian>
{
    SF_A = 0x0100;
};

Code above is to define an enum template that can adapt itself between 2 different byte orders. However, the compiler says, "An enum template declaration must refer to a previously declared class template member." What does it mean?

Is it possible to define an enum template, but requires a special syntax configuration?

CodePudding user response:

There are no enum templates in C .

You can achieve the desired effect by making the enum a member of some class template.

template <ByteOrder> class SF_Wrapper;
template <> class SF_Wrapper<LittleEndian> { enum SF ...

template <ByteOrder bo> using SF = SF_Wrapper<bo>::SF;

CodePudding user response:

There are no enum templates in C . The message is telling you that a workaround is to use an enum member in a class template instead.

However, I don't understand the purpose of SF. How would you use it? Why do the two specializations for SF_A need to have different types? It seems to just be usable as integer constant. In that case, why not simply define a constexpr uint16_t variable template?

  • Related