Search code examples
c++c++11enumstypedefusing

Is it possible to inject an enum into a classes scope/namespace?


With an enum Foo::Values and a class Bar outside of Foo, can I inject all values of the enum into class scope without redefining the type?

namespace Foo{
    enum Values{
        zero, one, two
    };
}

struct Bar{
    typedef Foo::Values Values; //Doesn't work, but is what I'd like to do
    using Foo::Values;          //Or this
}

So that these are valid:

Foo::Values val = Bar::zero;
assert(std::is_same<Foo::Values, Bar::Values>::value);

Is this possible?


Solution

  • This way:

    using Values = Foo::Values;
    

    Extracting the values is possible only one by one:

    static constexpr Values zero = Foo::zero;
    static constexpr Values one = Foo::one;
    static constexpr Values two = Foo::two;
    

    Check:

    #include <iostream>
    #include <type_traits>
    
    namespace Foo {
        enum Values { zero, one, two };
    }
    
    struct Bar {
        using Values = Foo::Values;
        static constexpr Values zero = Foo::zero;
        static constexpr Values one = Foo::one;
        static constexpr Values two = Foo::two;
    };
    
    int main() {
        Foo::Values val = Bar::zero;
        std::cout << std::is_same<Foo::Values, Bar::Values>::value;
    }
    

    Output:

    1