Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying a rule on how to increment an enum

Is there a way to change how an enum sets the values of its constants? Normally it's incrementing by one but I want to apply an other rule. In PAWN this would work

enum (<<=1) {
 a = 1,//0b001
 b,//0b010
 c//0b100
}

Is there a way to do this in C++?

like image 579
neophoenix Avatar asked Mar 02 '15 11:03

neophoenix


People also ask

Can you increment an enum?

Incrementing an enumeration requires a cast to convert the integer result of addition back to the enumeration type, as in: d = day(d + 1);

Do enums wrap around?

No. enum s are not designed to "wrap around" in the way you describe by default.

How many values can enum hold?

An ENUM column can have a maximum of 65,535 distinct elements.

What are enumeration variables in C?

Enumeration or Enum in C is a special kind of data type defined by the user. It consists of constant integrals or integers that are given names by a user. The use of enum in C to name the integer values makes the entire program easy to learn, understand, and maintain by the same or even different programmer.


2 Answers

not automatically, but you can specify manually each value

enum X {
  a = 0x01,
  b = 0x02,
  c = 0x04
};
like image 87
bolov Avatar answered Sep 26 '22 10:09

bolov


You could automate this shifting process using templates metaprogramming:

template<int by>
struct OneShlBy {
    enum { Value = OneShlBy<by - 1>::Value << 1 };
};

template<>
struct OneShlBy<0> {
    enum { Value = 1 };
};

enum X {
    a = OneShlBy<0>::Value,
    b = OneShlBy<1>::Value,
    c = OneShlBy<2>::Value
};
like image 28
sharptooth Avatar answered Sep 26 '22 10:09

sharptooth