1

I want to create an enum with 255 elements as follows:

enum class MyEnum
{
    Item0,
    Item1,

    //....

    Item254,
    Item255
};

Is there any way to generate the members of the enum using a macro instead of actually listing them all?

CuriousGeorge
  • 7,120
  • 6
  • 42
  • 74
  • 1
    TMP might be a better option – paulm Aug 23 '13 at 18:07
  • 1
    Pretty sure Boost PP sequences can do it. – chris Aug 23 '13 at 18:08
  • I'd just use copy paste. 255 really isn't that much... Unless you are worrying about the extra 258 lines in your source code or something I haven't thought about yet... – olevegard Aug 23 '13 at 18:09
  • just trying to avoid clutter – CuriousGeorge Aug 23 '13 at 18:11
  • 2
    What purpose would this enum serve - why use an enum for such a thing when the literal means the same thing (for example consider code where someone defined `ONE_THOUSAND` to hopefully be a useful constant and its value changes to `2000`). – Mark B Aug 23 '13 at 18:11
  • @albundy Can't you just place it in a separate header file? – olevegard Aug 23 '13 at 18:12
  • I could, but I would like the enum to be in the scope of another class: Class::MyEnum::Item0 – CuriousGeorge Aug 23 '13 at 18:13
  • ask yourself how long it would take you to write a shell script that spits out that code text. Is it less time than it takes to do it by hand? if so, there you go. (and it should take about two minutes to write *and* test). – WhozCraig Aug 23 '13 at 18:14
  • 1
    Place it in a different file and then include that file inside the `Class` definition. – mark Aug 23 '13 at 18:14
  • 1
    @albundy Even if a macro-based solution is possible (which I strongly doubt, because macros do not offer a viable compile-time programming environment), it's going to be ugly as hell. Whatever "clutter" you're talking about would look like the cleanest spot on earth in comparison to such a solution. – Sergey Kalinichenko Aug 23 '13 at 18:14
  • @MarkB You're totally right. Al, just use `typedef int MyEnum;`, don't worry about adding an 'Item' suffix. – IdeaHat Aug 23 '13 at 18:14
  • @chris - you are correct. BOOST_PP_ENUM_PARAMS does what I need. – CuriousGeorge Aug 23 '13 at 18:32
  • 1
    Still, I'm not sure it's the *best* solution. – chris Aug 23 '13 at 18:32
  • I wasn't asking for the "best solution" I was asking for BOOST_PP_ENUM_PARAMS =) – CuriousGeorge Aug 23 '13 at 18:34

2 Answers2

3

Well, it seems what the OP is after is BOOST_PP_ENUM_PARAMS. I won't say it's the best solution, but it does work for an enum with values like these:

enum class MyEnum {
    BOOST_PP_ENUM_PARAMS(256, Item)
};
chris
  • 60,560
  • 13
  • 143
  • 205
2

you might use shell script to generate them...i think they won't change often

echo Item{0..255}, 
Zoltán Haindrich
  • 1,788
  • 11
  • 20