mercredi 29 septembre 2021

C++ std::random and enum class

I've got a fussy question regarding more modern C++ "preferred" styles.

Say I want to use the contents of std::random in order to select a value from an enum class. How can I finagle that? We're talking some pretty basic stuff here, where the first selection works just fine, but Visual Studio scolds me (rightly) for using bare enums:

enum Direction:uint8_t {
    Left, Right
};

std::uniform_int_distribution<uint8_t> direction(Direction::Left, Direction::Right);

// and so on...

I was surprised enum-base works for a classic enum. But, simply adding the word class into the mix causes the whole shebang to fail to compile.

enum class Direction:uint8_t {
    Left, Right
};

std::uniform_int_distribution<uint8_t> direction(Direction::Left, Direction::Right);

// Severity Code    Description Project File    Line    Suppression State
// Error    C2338   invalid template argument for uniform_int_distribution:
//    N4659 29.6.1.1 [rand.req.genl]/1e requires one of short, int, long, long long, unsigned short, 
//    unsigned int, unsigned long, or unsigned long long 
//    C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\VC\Tools\MSVC\14.29.30133\
//    include\random    1863    

And so on. =)

I can certainly swallow my pride and principle for the sake of this homework, but goshdernit I wanted to abide by modern standards.

I'd be tickled pink if someone had some clever workaround or other best-practice-style-thing when one wants to shuffle an enum like this.

Thanks in advance!




Aucun commentaire:

Enregistrer un commentaire