views:

82

answers:

2

Hi all! I have a class, let's call it A. It has a enum (E) and a method Foo(E e), with gets E in the arguments. I want to write a wrapper (decorator) W for A. So it'll have its own method Foo(A::E). But I want to have some kind of encapsulation, so this method should defined as Foo(F f), where F is another enum defined in W, that can be converted to A::E. For example:

class A
{
  public:
    enum E { ONE, TWO, THREE };
    void Foo(E e);  
};

class B
{
  //enum F; // ???
  void Foo(F f)
  {
    a_.Foo(f);
  }

  private:
    A a_;
};

How F should be defined? I don't want to copy value like this:

enum F { ONE = A::ONE, TWO = A::TWO, THREE = A::THREE };

because its a potential error in the near feature. Is the typedef definition:

typedef A::E F;

is the best decision? Is it legal?

A: 

I think in order to enhance your program's simplicity, the better of the two choices you presented is to go with the typedef unless there's some compelling reason not to. I certainly don't recommend duplicating functionality (as your first approach seems to be doing) as that rapidly becomes a maintenance concern.

andand
+1  A: 

The problem with the typedef is that it doesn't make A go away. You wouldn't be able to say F f = B::ONE;, because B::ONE wouldn't exist. You'd still have to use A::ONE, etc. From what I understand, that's not what you want.

For what it seems like you're going for, creating a new enumeration in B is probably your best bet. The only things to beware of here are 1) you will need to type cast between A::E and B::F and 2) changes in one enumeration need to be mirrored in the other.

It wouldn't be necessary to copy the values the way you do, though. If A::E was:

enum E { ONE = 4, TWO = 7, THREE, FOUR, FIVE };

You could then copy and paste this to create B::F:

enum F { ONE = 4, TWO = 7, THREE, FOUR, FIVE };

However, the disadvantage of this copy & paste is that if I then decide to change A::TWO to be equal to ten, I would have to be sure to change B::TWO. If you defined B::F the way you showed ( ONE = A::ONE ... ), this wouldn't be a problem but it would be little bit more work.

DAG