https://rentry.org/PPP2_p286

// Code derived from Stroustrup's PPP2 book
// § 8.5.8 Function call implementation
//  -and beginning on p 286

#include <iostream>

using namespace std;

class Token {
 public:
  char kind = 'K';  // what kind of token
};

class Token_stream {
 public:
  Token get();  // get a Token (get() is defined elsewhere)

 private:
  Token buffer;
};

Token Token_stream::get() { return buffer; }

double term(Token_stream& ts);
double primary(Token_stream& ts);

double expression(Token_stream& ts)
{
  double left = term(ts);

  Token t = ts.get();

  // ...

  cout << t.kind << '\n';

  return left;
}

double term(Token_stream& ts)
{
  double left = primary(ts);

  Token t = ts.get();

  switch (t.kind) {
      // ...
    case '/': {
      double d = primary(ts);

      // ...

      cout << d << '\n';
    }
      // ...
  }

  return left;
}

double primary(Token_stream& ts)
{
  Token t = ts.get();

  switch (t.kind) {
    case '(': {
      double d = expression(ts);

      // ...

      cout << d << '\n';
    }
      // ...
  }

  return 0.0;
}

int main()
{
  Token_stream ts;

  expression(ts);
}

build & run:

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

PrevUpNext

Edit
Pub: 04 Apr 2023 15:06 UTC
Edit: 03 May 2023 00:39 UTC
Views: 512