Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <variant>
- #include <vector>
- enum Brace { Round, Square };
- enum Arity { Unary, Binary };
- enum Assoc { Left, Right };
- struct Op {
- char symbol;
- Arity ary;
- Assoc assoc;
- int prec;
- };
- struct Number { float n; };
- struct RealVar { std::string v; };
- struct BoolVar { std::string v; };
- struct Operator { Op op; };
- struct LeftParen { Brace b; };
- struct RightParen { Brace b; };
- struct Function { std::string f; };
- using Token = std::variant<Number, RealVar, BoolVar, Operator, LeftParen, RightParen, Function>;
- bool is_number(const Token& token) { return token.index() == 0; }
- bool is_real_var(const Token& token) { return token.index() == 1; }
- bool is_bool_var(const Token& token) { return token.index() == 2; }
- bool is_operator(const Token& token) { return token.index() == 3; }
- bool is_left_paren(const Token& token) { return token.index() == 4; }
- bool is_right_paren(const Token& token) { return token.index() == 5; }
- bool is_function(const Token& token) { return token.index() == 6; }
- std::ostream& operator<< (std::ostream &os, const Op &op) {
- return os << "Op(" << op.symbol << "," << op.ary << "," << op.assoc << "," << op.prec << ")";
- }
- std::ostream& operator<< (std::ostream &os, const Token &token) {
- if (is_number(token)) return os << "Number(" << std::get<Number>(token).n << ")";
- else if (is_real_var(token)) return os << "RealVar(" << std::get<RealVar>(token).v << ")";
- else if (is_bool_var(token)) return os << "BoolVar(" << std::get<BoolVar>(token).v << ")";
- else if (is_operator(token)) return os << "Operator(" << std::get<Operator>(token).op << ")";
- else if (is_left_paren(token)) return os << "LeftParen(" << std::get<LeftParen>(token).b << ")";
- else if (is_right_paren(token)) return os << "RightParen(" << std::get<RightParen>(token).b << ")";
- else if (is_function(token)) return os << "Function(" << std::get<Function>(token).f << ")";
- else return os;
- }
- int main() {
- std::vector<Token> tokens = {
- Number { 0.123456 },
- RealVar { "Rsomething" },
- BoolVar { "Bflag" },
- Operator { Op { '+', Binary, Left, 5 } },
- LeftParen { Square },
- RightParen { Square },
- Function { "exp" }
- };
- // print all
- std::cout << "my tokens: \n";
- for (const auto& token : tokens) {
- std::cout << token << "\n";
- }
- std::cout << "\nHello, World!\n";
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement