lundi 20 mai 2019

Why do I have to explicitly cast an enum that I have specified the underlying type for?

I recently learned that I can specify the underlying type of an enumerator in C++11.

I've noticed that I can't for example use an enumerator with an underlying type of uint16_t as an argument for a uint16_t parameter. See the following example:

#include <stdint.h>

enum class Apples : uint16_t
{
    GRANNY_SMITH = 1
};

class AppleWatcher
{
    uint16_t m_apple;
public:
    AppleWatcher(const uint16_t apple) : m_apple(apple) {};

};

int main()
{
    AppleWatcher(static_cast<uint16_t>(Apples::GRANNY_SMITH));  // This works

    AppleWatcher(Apples::GRANNY_SMITH); // Compiler error here

    return 0;
}

I still have to explicitly cast to the underlying type to use it in such cases, so what is the purpose of this feature?

Aucun commentaire:

Enregistrer un commentaire