#How to get a random enum class value?

28 messages · Page 1 of 1 (latest)

muted fernBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

honest seal
#

Each enum value is really an integer.

#

Orange is 0 and so on.

#

I'm talking about enum class.

#

enum class is just a safer and more featured version of enum.

dense cypress
#

believe you might want return static_cast<T>(index);

hazy goblet
#

@dense cypress I'm getting the same issue. It seems to be not liking T::_COUNT

dense cypress
#

oh, also update to int index = next(0, static_cast<int>(T::_COUNT) - 1);

#

tell me how that goes

#

if the compiler generates a warning or an error, tell me what it is

hazy goblet
#

That worked... nice!

#

Oh I see why. I mean, it has to cast _COUNT.

dense cypress
#

np! I think the problem was the implicit conversion from int to the enumeration type

hazy goblet
#

Yeah.

#

_COUNT is still a member of the enum class, so makes sense to cast it as well.

dense cypress
#

yup yup yup

hazy goblet
#

Thanks!

#

!solved

muted fernBOT
#

Thank you and let us know if you have any more questions!

This thread is now set to auto-hide after an hour of inactivity

late yew
# hazy goblet That worked... nice!

int to enum class doesn't get converted implicitly, that's exactly why enum class was introduced, but it still can be converted explicitly by a C-style cast, or by static_cast, they are equivalent here

#

(int)(T::_COUNT)

#

because writing static_cast and sending your code to friends who don't know what a static_cast is will make them feel
ExIsTeNtIaL AnXiEtY

late yew
#

C-style casts are used in intro to C++ classes where they teach students how to convert from double to int with casting, it won't cause anxiety

honest seal
#

That static_cast causes an uneasy feeling is an intentional design, it makes you think twice before using and it stands out to be found.

ivory musk
#

_COUNT is not a permissible name for an enumerator because all names starting with _A, _B, _C etc. are reserved

hot moss