Wednesday 7 July 2010

How to Extend existing enums

Picked up this very interesting example on extending enum's. The program is self explanatory and is as follows:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>

using namespace
std;

int
main()
{

enum
Enum1
{

value1,
value2,
value3,
final_value = value3
};


//Print out the enum values
cout<<"Enum1 values : ";
for
(int i = 0; i <= final_value; i++)
cout<<Enum1(i)<<" ";
cout<<endl;

enum
extendedEnum1
{

value4 = final_value + 1,
value5,
value6,
new_final_value = value6
};


//Print out the enum values
cout<<"extendedEnum1 values : ";
for
(int i = 0; i <= new_final_value; i++)
cout<<extendedEnum1(i)<<" ";
cout<<endl;

return
0;
}



The output is as follows:


1 comment:

  1. Or, you can do this:
    struct myenum
    {
    enum
    {
    val1,
    val2,
    val3
    };
    enum
    {
    nextval = val3 + 1
    };
    };

    struct my_extended_enum : myenum
    {
    enum
    {
    val4 = myenum::nextval,
    val5,
    val6
    };
    };

    int main(int argc, char* argv[])
    {
    int i = myenum::val1;
    int j = my_extended_enum::val1; //j == i
    j = my_extended_enum::val4; //j = 3
    return 0;
    }

    ReplyDelete