https://rentry.org/PPP2_p183

// Code derived from Stroustrup's PPP2 book
// § 6.3.3 Implementing tokens
//  -and beginning on p 183

#include <iostream>
#include <stdexcept>

using std::cerr;
using std::cout;
using std::exception;
using std::runtime_error;

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

// a very simple user-defined type
class Token {
 public:
  char   kind  = '0';
  double value = 0.0;
};

int main()
try {
  Token t;         // t is a Token
  t.kind = '+';    // t represents a +
  Token t2;        // t2 is another Token
  t2.kind  = '8';  // we use the digit 8 as the "kind" for numbers
  t2.value = 3.14;

  Token tt = t;  // copy initialization
  if (tt.kind != t.kind)
    error("impossible!");

  t = t2;                   // assignment
  cout << t.value << '\n';  // will print 3.14

} catch (exception& e) {
  cerr << "error: " << e.what() << '\n';
  return 1;

} catch (...) {
  cerr << "Oops: unknown exception!\n";
  return 2;
}

build & run:

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

PrevUpNext

Edit
Pub: 13 Mar 2023 04:35 UTC
Edit: 30 Apr 2023 07:27 UTC
Views: 351