例外処理の復習

PPPUC++のErrorの章を読んでいて、例外とかちゃんと理解してないなーということに気がついたり(遅い)。そうか単にオブジェクト投げるだけだから、階層構造を作って親で受ければ面白いわけですね。

#include <iostream>
#include <string>
#include <vector>
using namespace std;

enum Item {
    CAROT, ONION, BEEF, POKE, ORANGE, STRAWBERRY, SPAM
};


struct Material {virtual string what(){};};

struct Vegetable : public Material {};
  struct Carot: public Vegetable {string what() {return "carot";}};
  struct Onion: public Vegetable {string what() {return "onion";}};

struct Meat : public Material {};
  struct Beef : public Meat {string what() {return "beef";}};
  struct Poke : public Meat {string what() {return "poke";}};

struct Fruit : public Material {};
  struct Orange     : public Fruit {string what() {return "orange";}};
  struct Strawberry : public Fruit {string what() {return "strawberry";}};

struct Spam {string what() {return "spam";}} ;


void chef(Item order)
{
    // オーダー投げるよー
    switch (order) {
    case CAROT:
        throw Carot();
    case ONION:
        throw Onion();
    case BEEF:
        throw Beef();
    case POKE:
        throw Poke();
    case ORANGE:
        throw Orange();
    case STRAWBERRY:
        throw Strawberry();
    case SPAM:
        throw Spam();
    default:
        cout << "?????????? .... " << endl;
    }
}

int main()
{
    vector<Item> items = {CAROT, ONION, BEEF, POKE, ORANGE, STRAWBERRY, SPAM};
    while (! items.empty()) {
        try {
            chef(*items.begin()) ; // シェフー!
        // 受取る
        } catch (Vegetable& m) {
            cout << m.what() << "  Delicious...!" << endl;
        } catch (Meat& m) {
            cout << m.what() <<  "  Yummy----!" << endl;
        } catch (Fruit& m) {
            cout << m.what() << "  Sweet!!" << endl;
        } catch (...) {
            cout << "can i eat this? " << endl;
        }
        items.erase(items.begin());
    }
}

修行が足らん。。。
というか、シェフ、、オーダーを投げるな。
vectorの初期化を楽してるので、コンパイルにはgcc だと -std=c++0x が必要です。