toge's diary

コンピュータ関連の趣味をつらつらと。

なんとも格好悪いけどswitchを使ったfiber

そうこれは無茶苦茶制限されたfiberです。
fiber宣言内でのswitchが使えません。ついでに変数宣言しても保存されません。

でもこれで十分だなぁと思ってしまう今日この頃。所詮fiberで記述する部分は、変数処理か、コンポーネントの呼び出しといった、簡単なコードだからね。

ライブラリに依存しないので、当然ポータブルなので、これでいいやと妥協しております。
無意味にincludeしているのは__LINE__ではなく連番の数値にしたかったから。
そうすればswitchはテーブルジャンプになるからね。

もちっとまともにしたら公開します。

#define COBEGIN "fiber_start.h"
#define COSTOP  "fiber_stop.h"
#define COEND   "fiber_end.h"
#define YIELD   "fiber_yield.h"
#define RESUME(C)   (C(), C.live__coroutine())

struct Coroutine
{
protected:
  int line__coroutine_;
  bool live__coroutine_;

public:
  Coroutine()
    : line__coroutine_(0),
      live__coroutine_(true)
  {}

public:
  bool live__coroutine()
  {
    live__coroutine_;
  }

  virtual void operator()()
  {
    return;
  }
};

template 
struct Nat
  : public Coroutine	// generate all natural numbers
{
  int c;

#include COBEGIN
  {
#include YIELD()
	c = 0;
#include YIELD()
  	for(;;)
    {
#include YIELD()
      printf("Nat:yield start\n");
#include YIELD()
      printf("Nat:yield end\n");
#include YIELD()
    }
  }
  #include COEND
};

int main()
{
  Nat nat;

  for (int index = 0; index < 10; index++)
  {
    printf("before nat\n");

    int result;
    RESUME(nat);
    printf("%d\n", result);

    printf("after nat\n");
  }

  return 0;
}