2

I need to use the enumerator of the enum class multiple times in one block of code and I would like to avoid the classical enum from C++03.

enum class Color {RED, GREEN};
{
    Color::RED //this works
    RED;       //how do I make this work (only for this block)?
}

I tried using

using namespace Color;

but it obviously did not work since Color is not a namespace.

2
  • Try and look at this . stackoverflow.com/questions/2503807/… Commented Sep 26, 2015 at 7:54
  • That Q does not answer my question though. Commented Sep 26, 2015 at 7:58

1 Answer 1

4

This is impossible:

7.3.3p7 The using declaration [namespace.udecl] (n3337)

A using-declaration shall not name a scoped enumerator.

You can create a type alias using decltype:

using RED = decltype(red);

It does work in Clang, but is a reported bug.

The workaround is to use a variable.

Color red = Color::RED;

Rereading the question, it sounds like you want to bring all of the enum's variables into scope, not just one member. I suggest you read the proposal for enum class to see some of the issues it was trying to solve. The whole point of scoped enums is to avoid injecting its members into the enclosing scope.

So just use a regular enum.

Sign up to request clarification or add additional context in comments.

7 Comments

Well thats a bit cumbersome. Moreover I cant use that in a switch statement like I wanted to.
@Slazer You can make red constexpr.
I can not use regular enums, because i have two enums and both of them have one enumerator with the same name. I use one enum in one function and the other in another function. I want to use it because of type safety (2.1 in the proposal). I dont want any "color++" or "color=3" going on.
@Slazer color++ or color=3 wouldn't work on a regular enum either.
I know but one can override that with -fpermissive, which one will do. In C++11 its a showstopper. This was just one reason though. The problem would not be solved with enums anyways as I said.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.