logo

libbulletml

Library of Bullet Markup Language (forked from https://shinh.skr.jp/libbulletml/index_en.html )git clone https://anongit.hacktivis.me/git/libbulletml.git/

formula.h (1680B)


  1. /// 数式クラス
  2. #ifndef FORMULA_H_
  3. #define FORMULA_H_
  4. #include "bulletmlcommon.h"
  5. template <typename Val_>
  6. class AbstractNumber {
  7. public:
  8. DECLSPEC virtual Val_ value() const =0;
  9. DECLSPEC virtual ~AbstractNumber() {}
  10. };
  11. template <typename Val_>
  12. class Number : public AbstractNumber<Val_> {
  13. public:
  14. DECLSPEC explicit Number(Val_ val) : val_(val) {}
  15. DECLSPEC virtual Val_ value() const { return val_; }
  16. private:
  17. Val_ val_;
  18. };
  19. typedef enum { op_null =0, op_add, op_sub, op_mul, op_div } Operator;
  20. template <typename Val_>
  21. class Formula : public AbstractNumber<Val_> {
  22. private:
  23. typedef AbstractNumber<Val_> ANumber;
  24. public:
  25. DECLSPEC virtual ~Formula() {
  26. delete lhs_;
  27. delete rhs_;
  28. }
  29. /// public だけど呼ばないで下さい。
  30. /**
  31. * @todo yacc の使いかたを調べて、これを private に
  32. */
  33. //@{
  34. DECLSPEC explicit Formula(ANumber* val)
  35. : lhs_(val), rhs_(0), op_(op_null), headsub_(false) {}
  36. DECLSPEC Formula(ANumber* lhs, Operator op, ANumber* rhs)
  37. : lhs_(lhs), rhs_(rhs), op_(op), headsub_(false) {}
  38. DECLSPEC Formula* setHeadSub() { headsub_ = true; return this; }
  39. //@}
  40. DECLSPEC virtual Val_ value() const {
  41. if (headsub_) return -valueBeforeHeadSub();
  42. else return valueBeforeHeadSub();
  43. }
  44. private:
  45. Val_ valueBeforeHeadSub() const {
  46. switch (op_) {
  47. case op_null:
  48. return lhs_->value();
  49. case op_add:
  50. return lhs_->value() + rhs_->value();
  51. case op_sub:
  52. return lhs_->value() - rhs_->value();
  53. case op_mul:
  54. return lhs_->value() * rhs_->value();
  55. case op_div:
  56. return lhs_->value() / rhs_->value();
  57. default:
  58. return 0; // avoid warning
  59. }
  60. }
  61. private:
  62. ANumber *lhs_, *rhs_;
  63. Operator op_;
  64. bool headsub_;
  65. };
  66. #endif // ! FORMULA_H_