1

Hi I'm trying to have enum outside of class but inside namespace AND have them have different definition depending on some condition. How can I achieve this? (C++)

For example something like this

namespace fruit  {
    if (season) {
      enum eAvailfruit
      {
        apple,
        banana,
        cNumFruit
      };
    } else {
      enum eAvailfruit
      {
        watermelon,
        grape,
        peach,
        cNumFruit
      };
    }
}

Is there a way ??

8
  • I imagine so if season is a compile-time constant, but not otherwise. Commented Feb 24, 2014 at 16:51
  • What is the scope of the condition, season? Commented Feb 24, 2014 at 16:55
  • 8
    But how will you deal with code that used the enum? For example, if you've got code that mentions banana then what will happen when season is false? Commented Feb 24, 2014 at 16:58
  • 8
    That all sounds like a baaaad design idea. May be a XY-problem, what are you actually about to solve? Commented Feb 24, 2014 at 17:00
  • 2
    @user2134081 "all the code that references banana will be also under if (season) throughout the code" That sounds like you are about to have a lot of duplicate code. Commented Feb 24, 2014 at 17:25

1 Answer 1

4

One approach would be to use the preprocessor:

#ifdef SUMMER
enum Fruit {
    // ....
};
#else
enum Fruit {
    // ...
};
#endif

and then pass a compile-time constant in whatever way your compiler normally prefers it, for example the -D flag in gcc.

Or, on the other hand, don't, because it's a terrible idea. One slightly better solution might be the following:

enum Season {
    Spring,
    Summer,
    Autumn,
    Winter
};

template <Season S>
struct fruit; // undefined

template <>
struct fruit<Spring>
{
    enum AvailableFruit {
        Banana,
        // etc
    };
};

template <>
struct fruit<Summer>
{
    enum AvailableFruit {
         // etc
    };
};

// etc, specialisations for Autumn and Winter

These structs are then fairly similarly to C++11 scoped enums, in that you can refer to (for example) fruit<Spring>::Banana, but they're type safe as it's illegal to refer to just plain Banana, or even just plain AvailableFruit.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.