ritsch_master
ritsch_master

Reputation: 13

Many Enums with same members in the same class

The title says it all, but I give an example here:

class A {
public:
  enum A 
  {
    enumVal1,
    enumVal2
  };

  enum B 
  {
    enumVal1,
    enumVal3,
  };
};

What do I have to do that this may work?

Thanks in advance.

Upvotes: 1

Views: 85

Answers (3)

Potatoswatter
Potatoswatter

Reputation: 137780

C++11 has scoped enumerations:

class S {
public:
  enum class A 
  {
    enumVal1,
    enumVal2
  };

  enum class B 
  {
    enumVal1,
    enumVal3,
  };
};

Then you need to refer to A::enumVal1 and B::enumVal1. enumVal2 must also be qualified even though there is no ambiguity. Also, the enumerators do not implicitly convert to and from int as in the old style; you need a static_cast.

This is just reifying a C++03 idiom:

class S {
public:
  struct A { enum type
  {
    enumVal1,
    enumVal2
  } value; };

  struct B { enum type 
  {
    enumVal1,
    enumVal3,
  } value; };
};

Then you need to either declare objects of type A::type and B::type, or refer to the .value member of struct A. (Other approaches are possible.)

Upvotes: 1

Andrew
Andrew

Reputation: 24846

In c++ 11 you can use enum class:

class MyClass {
public:
  enum class A 
  {
    enumVal1,
    enumVal2
  };

  enum class B 
  {
    enumVal1,
    enumVal3,
  };
};

Than you reference the values as:

MyClass::A::enumVal1
MyClass::B::enumVal1

Using enum classes instead of old enums also gives you strong typing. You can read more about enum classes here

Upvotes: 4

Luke
Luke

Reputation: 7210

C++ doesn't allow you to have two identical identifiers in the same scope. You could add a prefix to make it clear:

  enum A 
  {
    A_enumVal1,
    A_enumVal2
  };

  enum B 
  {
    B_enumVal1,
    B_enumVal3
  };

Or you could put each enum in a different namespace and use A::enumVal1, B::enumVal1, etc. Namespaces were designed to solve problems like this.

Upvotes: 4

Related Questions