Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to iterate over an enum without knowing its size in c++

Tags:

c++

c++11

Hello I have the following enum

enum params_Solver {
  params_Solver_Lorem,
  params_Solver_Ipsum,
  params_Solver_Simply,
  params_Solver_Dummy,
  params_Solver_Test,
  params_Solver_Typesetting,
  params_Solver_Industry,
  params_Solver_Scrambled
};

what I want to do is try to doing something like this pseudocode:

for (auto enum_member: params_Solver)
{
    print(index, enum_member); // output looks like this: "0, params_Solver_Lorem", "1, params_Solver_Ipsum" etc
}

Is there anyway to achieve this?

Edit: I do not have the control over enum. This enum is provided by a different file from a 3rd part library. I can probably copy it but not change the original enum. I want to write the members of the enum library to a different file.

like image 563
Morpheus Avatar asked Dec 08 '25 15:12

Morpheus


1 Answers

No. At least not directly. Enums are actually not a set of constants. Rather they are a type that comes with a set of named constants. Difference is: for example 42 is a completely valid value of params_Solver, it just has no name.

A common way to enable iteration is to add a sentinel value:

enum params_Solver {
  params_Solver_Lorem,
  params_Solver_Ipsum,
  params_Solver_Simply,
  params_Solver_Dummy,
  params_Solver_Test,
  params_Solver_Typesetting,
  params_Solver_Industry,
  params_Solver_Scrambled,
  num_params_Solver          // <----
};

And then iterate from 0 till num_params_Solver. The nice thing is that you can add another constant and num_params_Solver will still be correct. The limitation is that it only works for enums without custom values.

like image 111
463035818_is_not_a_number Avatar answered Dec 10 '25 04:12

463035818_is_not_a_number