Search code examples
c++enumsusing-declaration

A 'using' declaration with an enum


A using declaration does not seem to work with an enum type:

class Sample{
    public:
        enum Colour {RED, BLUE, GREEN};
}

using Sample::Colour;

does not work!

Do we need to add a using declaration for every enumerators of enum type? Like below:

using sample::Colour::RED;

Solution

  • A class does not define a namespace, and therefore "using" isn't applicable here.

    Also, you need to make the enum public.

    If you're trying to use the enum within the same class, here's an example:

    class Sample {
     public:
      enum Colour { RED, BLUE, GREEN };
    
      void foo();
    }
    
    void Sample::foo() {
      Colour foo = RED;
    }
    

    And to access it from outside the class:

    void bar() {
      Sample::Colour colour = Sample::RED;
    }