Home > other >  How do you bring all enum constants into scope?
How do you bring all enum constants into scope?

Time:11-28

Is there a way to bring all enum constants into scope? I don't mean the type, I mean the constants themselves.

struct Foo {
    enum Bar {
        A = 1, B = 2, C = 4, D = 8
    };
};

int main() {
    using E = Foo;
    int v = E::A | E::B | E::C | E::D;

    // But is it possible to instead do...
    using Foo::Bar::*; // (not real C  )
    int v = A|B|C|D; // <-- all enum constants are brought into scope
}

CodePudding user response:

// This already works, of course.
using E = Foo;
Foo::Bar v = E::A | E::B | E::C | E::D;

Well, not really, because E::A | E::B | E::C | E::D is an int and you can't implicitly convert an int to an enum.

But that's not stopping you from using 's using enum (unless you can't use C 20):

struct Foo {
    enum Bar {
        A = 1, B = 2, C = 4, D = 8
    };
};

int main() {
    using enum Foo::Bar; // (real C  20!)
    Foo::Bar v = D; 
}
  •  Tags:  
  • c
  • Related