Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access enum values in C++98 and C++11

I have a set of enum values defined in the "Foo" class (below).

namespace Fii
{
    class Foo 
    {
        struct Bar
        {
            enum Baz
            {
                BAZ1,
                BAZ2, 
                BAZ3
            };
        };
    };
};

I am using a struct to reduce the scope of Baz enum values as well as show there are a group of related values.

My objective is to assign a value from an enum type to a variable. Using the class definition above, one can do this:

Fii::Foo::Bar::Baz myValue = Fii::Foo::Bar::BAZ1 (Works in both C++98 and C++11)

However, I feel that:

  • At first glance, myValue seems to be initialized as a Fii::Foo::Bar but this is just because enum are a hack to group related constants in the parent (Bar in this case)

To improve readiness, I I re-factored the code to:

namespace Fii
{
    class Foo 
    {
        enum Baz
        {
            BAZ1,
            BAZ2, 
            BAZ3
        };
    };
};

Using this new class definition, one can do this:

Fii::Foo::Baz myValue = Fii::Foo::Baz::BAZ1 (Works in C++11 only)
Fii::Foo::Baz myValue = Fii::Foo::BAZ1 (Should work on C++98 and C++11 - not tested)

Q1) Why is Fii::Foo::Bar::Baz myValue = Fii::Foo::Baz::BAZ1 only working on C++11 ?

Q2) In C++98, is there a way to write Fii::Foo::Baz myValue = Fii::Foo::Baz::BAZ1 ? You are allowed to make any changes you like in the class definition.

Environment: - Clang compiler with C++11 support - Xcode 4 - Mac OS OS 10.8

like image 608
David Andreoletti Avatar asked Sep 12 '12 05:09

David Andreoletti


People also ask

How do you find the enum value of an enum?

Get the value of an Enum To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.

Can two enums have the same value in C?

Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.

Can you index an enum in C?

Yes, but unlike an enum, you have to specify a type for the values. You also have to make sure the index won't be higher than the number of cells.

Can enum be subclassed?

You can't do it, since the language does not allow you. And for a good logical reason: subclassing an enum would only make sense if you could remove some enum values from the subclass, not add new ones. Otherwise you would break the Liskov Substitution Principle.


1 Answers

C++11 adds class enums. It also adds a new way of accessing old-style enum values, which is what you are seeing here.

enum Foo { FOO1, FOO2, FOO3 }; // old-style enum

Foo f1 = Foo::FOO1; // OK in C++11, error in C++98.
Foo f2 = FOO1; // OK in C++98 and C++11 (for backward compatibility)
like image 177
juanchopanza Avatar answered Sep 21 '22 19:09

juanchopanza