https://rentry.org/PPP2_320

// Code derived from Stroustrup's PPP2 book
// § 9.5.1 “Plain” enumerations
//  -and beginning on p 320

#include <iostream>
#include <stdexcept>

using namespace std;

void error(const char* s) { throw runtime_error(s); }

enum Month {  // note: no “class”
  jan = 1,
  feb,
  mar,
  apr,
  may,
  jun,
  jul,
  aug,
  sep,
  oct,
  nov,
  dcm  // note dec changed to dcm to make it compile, see comment on p. 321
};

enum Day { monday, tuesday, wednesday, thursday, friday, saturday, sunday };

Month int_to_month(int x)
{
  if (x < jan || dcm < x)
    error("bad month");

  return Month(x);
}

void f(int m)
{
  [[maybe_unused]] Month mm = int_to_month(m);

  // ...
}

int main()
try {
  Month                  m  = feb;         // OK: feb in scope
  [[maybe_unused]] Month m2 = Month::feb;  // also OK

  // m = 7;  // error: can’t assign an int to a Month

  [[maybe_unused]] int   n  = m;         // OK: we can 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;
}

//------------------------------------------------------------------------------

void do_something() {}
void do_something_else() {}

void my_code([[maybe_unused]] Month m)
{
  // if (m == 17)  // huh: 17th month?
  //   do_something();

  // if (m == monday)  // huh: compare month to Monday?
  //   do_something_else();
}

build & run:

g++ -std=c++20 -O2 -Wall -pedantic ./ch_09/main_p320.cpp && ./a.out

PrevUpNext

Edit
Pub: 06 Apr 2023 17:30 UTC
Edit: 03 May 2023 01:13 UTC
Views: 645