views:

382

answers:

3

using declaration does not seem to work with enum type

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

using Sample::Colour;

does not work!! do we need to add using declaration for every enumerators of enum type? like below

using sample::Colour::RED;
+7  A: 

A class does not define a namespace, 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 without the class:

void bar() {
  Sample::Colour colour = Sample::RED;
}
Steve Lacey
+3  A: 

C++ Standard, 7.3.3.1:

The member name specified in a using-declaration is declared in the declarative region in which the using-declaration appears. [ Note: only the specified name is so declared; specifying an enumeration name in a using-declaration does not declare its enumerators in the using-declaration’s declarative region. —end note ]

Igor Semenov
C++ Standard or A Night at the Opera? (Sorry, couldn't resist).
Gorpik
Could you explain me this idiom, I'm not very strong in English? :)
Igor Semenov
I am not sure the standard is written in English. Looks a lot like lawyer speak :-)
Martin York
Actually, I meant "C++ Standard or A Night at the Opera?"
Igor Semenov
+3  A: 

To add to Stevela's answer, the problem with the original code is that you refer to a member, but the using declaration is not itself a member declaration:

7.3.3/6 has:

A using-declaration for a class member shall be a member-declaration.

To highlight this, the following example does work:

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

class Derived : public Sample
{
public:
  using Sample::Colour;  // OK
};

Finally, as pointed out by Igor Semenov here, even if you move the enum definition into a namespace, thereby allowing the using declaration, the using declaration will only declare the name of the enum type into the namespace (The 2003 standard reference is 7.3.3/2).

namespace Sample
{
  enum Colour { RED,BLUE,GREEN};
}

using Sample::Colour;
using Sample::BLUE;


void foo ()
{
  int j = BLUE; // OK
  int i = RED;  // ERROR
}
Richard Corden