tags:

views:

80

answers:

2

How do I randomly select a value for an enum type in C++? I would like to do something like this.

enum my_type(A,B,C,D,E,F,G,h,J,V);
my_type test(rand() % 10);

But this is illegal... there is not an implicit conversion from int to an enum type.

+6  A: 

How about:

enum my_type {
    a, b, c, d,
    last
};

void f() {
    my_type test = static_cast<my_type>(rand() % last);
}
zildjohn01
+1 for less hard-coding, but I recommend the C++ style static_cast.
Bill
Of course, my C++ is rusty, good catch.
zildjohn01
+2  A: 

There is no implicit conversion, but an explicit one will work:

my_type test = my_type(rand() % 10);
Mike Seymour