tour cpp: std::variant 实现无继承层次的访问者模式

std::variant 是基于模板而实现的一种包括了一个标志位的高级union对象;可以完全替代如下场景:

struct st {
    int type;
    union un {
        int i;
        float f;
    };
};
#include <iostream>
#include <variant>

template <class... base>
struct overloaded : base... {
  using base::operator()...;
};
template <class... base>
overloaded(base...) -> overloaded<base...>;

// struct checker;
struct Declaration {
  // void accept(checker *ckr) {
  //     std::cout << "Declaration accept it" << std::endl;
  // }
  int declaration_type{0};
};
struct Expression {};
struct Statement {};

using Node = std::variant<Declaration *, Expression *, Statement *>;
struct checker {
  void visit(Node node);
};

void checker::visit(Node node) {
  Declaration *declaration{};
  if (std::holds_alternative<Declaration *>(node) and
      (declaration = std::get<Declaration *>(node))) {
    std::cout << "declaration_type: " << declaration->declaration_type
              << std::endl;
  }  // else if ...
}

int main() {
  checker ckr;
  Declaration declaration{.declaration_type = 2};
  Node node{&declaration};
  ckr.visit(node);
  return 0;
}
posted @ 2024-10-11 20:11  joel-q  阅读(9)  评论(1编辑  收藏  举报