C++中的模式匹配

Pattern matching in C++

本文关键字:模式匹配 C++      更新时间:2023-10-16

我正在用C++编写编译器,与任何编译器一样,它需要大量的模式匹配和动态强制转换。在 Rust、Haskell 和 OCaml 等语言中,我可以轻松破坏一个类型,例如:

match node {
    Binary{ left, right, operator } => { .. }
    _ => { .. }
}

C++我能做的最好的事情就是:

if (auto bin = dynamic_cast<Binary*>(node)) { ... }
else if (...) { ... }

如果你在场景中引入智能指针,这真的很有限和丑陋。例如,如果我需要为某事匹配 2 件事:

bool matched = false;
if (auto m1 = dynamic_cast<Foo*>(a)) {
    if (auto m2 = dynamic_cast<Bar*>(b)) {
        matched = true;
    }
}
if (!matched) {
    // This is because C++ does not allow you to declare two variables inside the condition...
}

我知道 Mach7 库,但老实说,它似乎很糟糕,因为您需要为您的结构编写元数据(我也注意到它有很多错误和限制(。

有没有办法使这些匹配更具可读性?

以下似乎是避免两场比赛双打的方法 - 并且可以很容易地概括:

template <class T1,class T2> struct castPairstruct : public std::pair<T1,T2> {
     operator bool() {return first && second;}
     castPairstruct<T1,T2>(T1 a,T2 b):std::pair<T1,T2>(a,b) {;}
};
template <class T1,class T2> castPairstruct<T1,T2> castPair(T1 a,T2 b){
    return castPairstruct<T1,T2>(a,b);
}
if (auto j=castPair(dynamic_cast<Foo*>(a),dynamic_cast<Bar*>(b)) {