How do you bring all enum constants into scope?

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
}

Upvotes: 3

Views: 477

Answers (2)

Pepijn Kramer
Pepijn Kramer

Reputation: 12847

I misunderstood the question at first. If you are stuck pre C++20, I've used this workaround in the past.

#include <iostream>

//-----------------------------------------------------------------------------

namespace foo
{
    namespace bar
    {
        enum class Bar 
        {
            A = 1, 
            B = 2, 
            C = 4, 
            D = 8
        };

        // define some constants in namespace bar with the same values as the 
        // enum values. this will maintain typesafety of function calls.
        // but allows you to type using namespace foo::bar
        // to access these values
        
        constexpr Bar A = Bar::A;
        constexpr Bar B = Bar::B;
        constexpr Bar C = Bar::C;
        constexpr Bar D = Bar::D;
    }
}
//-----------------------------------------------------------------------------

using namespace foo::bar;

// function to show type of enum class can still be used as before
void function(const Bar enum_value)
{
    std::cout << static_cast<int>(enum_value);
}

// function for oring Bar's
Bar operator|(const Bar a, const Bar b)
{
    return static_cast<Bar>(static_cast<int>(a) | static_cast<int>(b));
}

// and a main to show it all
int main()
{
    function(A|B|C|D); // outputs 15
    return 0;
}

Upvotes: 1

Fureeish
Fureeish

Reputation: 13424

// 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; 
}

Upvotes: 8

Related Questions