Skip to content

Instantly share code, notes, and snippets.

@BroVic
Last active April 21, 2019 23:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BroVic/dd0dd2d91d7569f6e722006b003a7f25 to your computer and use it in GitHub Desktop.
Save BroVic/dd0dd2d91d7569f6e722006b003a7f25 to your computer and use it in GitHub Desktop.
Scoped and Unscoped Enumerations
// Scoped and Unscoped Enumerations
#include <iostream>
#include <array>
#include <string_view> // C++ 17
enum EShape
{
eCircle,
eSquare,
eTriangle,
eRectangle,
ePentagon,
eHexagon,
eSeptagon,
eOctagon,
eNonagon,
eDecagon
};
enum class ECShape
{
eCircle,
eSquare,
eTriangle,
eRectangle,
ePentagon,
eHexagon,
eSeptagon,
eOctagon,
eNonagon,
eDecagon
};
void showNumber(int);
void showNumber(ECShape);
void print(int);
std::string_view getName(int);
std::string_view getName(ECShape);
int main()
{
EShape shape = eCircle;
ECShape cShape = ECShape::eCircle;
showNumber(shape);
showNumber(cShape);
showNumber(eTriangle);
showNumber(ECShape::eHexagon);
auto shapeName1 = getName(eOctagon);
auto shapeName2 = getName(ECShape::ePentagon);
std::cout << "Shape 1 is " << shapeName1 << " while Shape 2 is " << shapeName2 << ".\n";
std::cin.get();
}
static std::string_view leftText = "Shape is number ";
static std::string_view rightText = " on the list.\n";
static std::array<std::string_view, 10> scShapes {
"Circle",
"Square",
"Triangle",
"Rectangle",
"Pentagon",
"Hexagon",
"Septagon",
"Octagon",
"Nonagon",
"Decagon"
};
// Displays a message with the value of the enumerator; integer type input
void showNumber(int val)
{
print(val);
}
// Displays a message with the value of the enumerator; ECShape type input
void showNumber(ECShape val)
{
print(static_cast<int>(val));
}
// Prints the mesage
void print(int p)
{
std::cout << leftText << p << rightText;
}
// Returns the name of a shape for a given enumerator; integer input type
std::string_view getName(int eShape)
{
return scShapes.at(eShape);
}
// Returns the name of a shape for a given enumerator; ECShape input type
std::string_view getName(ECShape eShape)
{
return scShapes.at(static_cast<int>(eShape));
}
@BroVic
Copy link
Author

BroVic commented Apr 21, 2019

Thanks to @BiCapitalization for the tip on string_view.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment