Littlebitter
Littlebitter

Reputation: 701

Use enum from other class without classname::

I have enum inside public part of some class A. I want to use this enum in class B. Is it a way to make it accessible without specifying *A::enum_value*? So I can use just *enum_value*.

using A::enumname;

inside class B doesn't compile.

Upvotes: 1

Views: 1046

Answers (2)

Mark B
Mark B

Reputation: 96243

There's no good way to directly import all the enum values from one place to another. In this case I'd suggest wrapping A's enum into a nested class, and then typedeffing that into B.

For example:

class A
{
public:
    struct UsefulEnumName
    {
        enum Type { BAR };
    };
};

class B
{
    typedef A::UsefulEnumName UsefulEnumName;
    UsefulEnumName::Type foo() const { return UsefulEnumName::BAR; }
};

Upvotes: 0

Vaughn Cato
Vaughn Cato

Reputation: 64308

If you only need certain values, you can do:

struct B {
  static const A::enumname 
    enum_value1 = A::enum_value1,
    enum_value2 = A::enum_value2;  // etc.
};

If you can modify A, you can extract the enum into a base class that can be used by both A and B:

struct AEnum {
  enum enumname { enum_value1, enum_value2 };
};

struct A : AEnum {
};

struct B : BEnum {
};

Upvotes: 1

Related Questions