Search code examples
c++c++11randomenum-class

Is there any way to get random from enum class in c++?


I want to fill a variable with random element from enum class.

So I tried set enum class type to int and pass last enum from enum class to rand:

enum class Enumerator: int
{
    en1=0,
    en2,
    en3,
    ensCount
};

int main()
{
    srand(time(NULL));
    auto a=static_cast<Enumerator>(rand()%Enumerator::ensCount);
    return 0;
}

Result is "no match for «operator%» (operand types are «int» and «Enumerator»)" error.


Solution

  • The operands of the built-in modulo (%) operator should be integral or unscoped enumeration type.

    Enumerator is a scoped enumeration.

    There are no implicit conversions from the values of a scoped enumerator to integral types.
    So you have to use static_cast to obtain the numeric value of the enumerator.

    int divisor = static_cast<int>(Enumerator::ensCount);
    srand(time(NULL));
    auto a = static_cast<Enumerator>(rand() % divisor);