tags:

views:

154

answers:

4

How can I use C++ enum types like C# ?

consider following definition in c++ :

enum myEnum { A, B, C};
myEnum en = A;

Now I want write line #2 as following line like C# :

myEnum en = myEnum.A;

??

A: 

What exactly is the question here? Your C# example will work as you have written it (although it doesn't match the .NET naming conventions...)

thecoop
I think he wants to use the C# syntax in C++.
Jim Mischel
+5  A: 

Well, different rules in C++. Closest you could get is this slight abomination:

namespace myEnum {
    enum myEnum { A, B, C};
}

myEnum::myEnum en = myEnum::A;
Hans Passant
It is a very nice solution. But is there any other solution without using namespace ?
Behrouz Mohamadi
Why? The namespace solution as posted works fine.
DeadMG
+5  A: 

C++0x introduces enum class that does exactly what you want:

enum class myEnum { A, B, C };
myEnum en = myEnum::A;

In C, I would probably use good old prefixing:

enum myEnum { myEnum_A, myEnum_B, myEnum_C };
myEnum en = myEnum_A;
FredOverflow
Now, Please tell me how can I do this in C ?
Behrouz Mohamadi
Your question has C++ tagged and you said C++, but now you say C?
DeadMG
@Behrouz: C doesn't have namespaces or scoping like this. You can't.
Billy ONeal
A: 

C++0x introduces enum class that does exactly what you want:

enum class myEnum { A, B, C }; myEnum en = myEnum::A;

In C, I would probably use good old prefixing:

enum myEnum { myEnum_A, myEnum_B, myEnum_C }; myEnum en = myEnum_A;

webgunner