// Code derived from Stroustrup's PPP2 book
// § 9.5 Enumerations
// -and beginning on p 318
#include <iostream>
#include <stdexcept>
using namespace std;
void error(const char* s) { throw runtime_error(s); }
enum class Month {
jan = 1,
feb,
mar,
apr,
may,
jun,
jul,
aug,
sep,
oct,
nov,
dec
};
enum class Day {
monday,
tuesday,
wednesday,
thursday,
friday,
saturday,
sunday
};
Month int_to_month(int x)
{
if (x < int(Month::jan) || int(Month::dec) < x)
error("bad month");
return Month{x};
}
void f(int m)
{
[[maybe_unused]] Month mm = int_to_month(m);
// ...
}
int main()
try {
[[maybe_unused]] Month m = Month::feb;
// Month m2 = feb; // error: feb is not in scope
// m = 7; // error: can’t assign an int to a Month
// int n = m; // error: can’t assign a Month to an int
[[maybe_unused]] Month mm = Month(7); // convert int to Month (unchecked)
// Month bad = 9999; // error: can’t convert an int to a Month
f(4);
f(99); // run-time error: bad month
} catch (exception& e) {
cerr << "error: " << e.what() << '\n';
return 1;
} catch (...) {
cerr << "Oops: unknown exception!\n";
return 2;
}