views:

166

answers:

3

I'm working with a legacy class that looks like this:

class A
{
    enum Flags { One = 1, Two = 2 };
};

I'd like to pull out all the enums into a new namespace defined in a new header:

// flags.h

namespace flags {

enum Flags { One = 1, Two = 2 };

};

Then pull these enums back into the class so that I can include just the flags.h in headers that only require these values (rather than the entire class definition):

// a.h

#include "flags.h"

class A
{
    using namespace flags;
};

How should I be doing this?

A: 
class F {
  enum Flags { One = 1, Two = 2 };
};


class A : public F {
};
Alexey Malistov
Misuse of inheritance spotted... could you at least gives F `protected` constructors and destructors?
Matthieu M.
+2  A: 

A using directive is illegal at class scope. Instead of a namespace you could define a class and then inherit from it:

struct flags {
    enum Flags { One=1, Two=2 };
};

class A : public flags { ... };

But this looks like a misuse of inheritance to me, to be honest. As an alternative you could bite the bullet and use a namespace without "importing" the names into class A.

sellibitze
Bite the bullet is the best option, though I still prefer `struct` encapsulation that `namespace` one, for struct interact with templates in a way namespace do not.
Matthieu M.
how could the struct style namespace ever be an advantage with templates? As is see it the struct just allows you two ways to do the same thing. template from the struct namespace or the enum type. Whereas a more standard use of namespace allows only one. More ways to do the same thing is only desired when writing perl.
caspin
+1  A: 

You can't make them all visible in a class without pulling the values in seperately via using declarations.

The best thing, in my opinion, that you can do is wrapping them in a class that contains nothing else. That way you can make them visible in another class by deriving from the class that holds the enums:

struct Holder {
   enum E { a };
protected:
   Holder() {}
   ~Holder() {}
};

class User : public Holder 
{
public:
   void f() { /* a is visible here */ }
};

void f() { /* User::a is visible here */ }
Georg Fritzsche
Misuse of inheritance spotted... could you at least gives F `protected` constructors and destructors?
Matthieu M.
You mean `Holder`? Point taken.
Georg Fritzsche