Showing posts with label enum. Show all posts
Showing posts with label enum. Show all posts

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:


Extending enums

There might come a scenario where you want to include an enum into a another one where the first one is a subset.

#include
struct enum_a {
     enum constant {
         a, b, c, d,
         end_of_enum_a = d
     };
};
struct enum_b : public enum_a {
     enum constant {
         e = end_of_enum_a + 1,
         f, g, h
     };
};
int main() {
     std::printf("enum_a: a(%d), b(%d), c(%d), d(%d)\n",
         enum_b::a, enum_b::b, enum_b::c, enum_b::d);
     std::printf("enum_b: e(%d), f(%d), g(%d), h(%d)\n",
         enum_b::e, enum_b::f, enum_b::g, enum_b::h);
     return 0;
}

Inheritance to the rescue. :-)

Simple example of BitSets in C++

From "The C++ Standard Library" By Nicolai M Josuttis: A bitset is a bitfield with an arbitrary but fixed number of bits. You can consider it a container for bits or Boolean values. Note that the C++ standard library also provides a special container with a variable size for Boolean values: vector.

Lets write a simple program using rainbow colours.


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Simple example of BitSets
#include<iostream>
#include<bitset>

using namespace
std;

int
main()
{

enum
Colour {red, orange, yellow, green, blue, indigo, violet, numOfColours};

bitset<numOfColours> usedColours;

usedColours.set(red);
usedColours.set(blue);

//Lets see the output
cout << "bitfield of used colours: " << usedColours << endl;
cout << "number of used colors: " << usedColours.count() << endl;
cout << "bitfield of unused colors: " << ~usedColours << endl;

//If any colour is used
if (usedColours.any())
{

// loop over all colors
for (int c = 0; c < numOfColours; ++c)
if
(usedColours[(Colour)c])
cout << Colour(c)<< " used "<<endl; //No way to print enum names directly
}

return
0;
}

The output is as follows:


Reference:


Check out this stream