Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C+中的模式匹配+; 我在C++中编写编译器,作为编译器,它需要大量的模式匹配和动态转换。在Rust、Haskell和OCaml等语言中,我可以轻松销毁类型,如: match node { Binary{ left, right, operator } => { .. } _ => { .. } } C++中我能做的最好的是: if (auto bin = dynamic_cast<Binary*>(node)) { ... } else if (...) { ... } if(auto bin=dynamic_cast(node)){…} 如果(…){…}_C++_Pattern Matching - Fatal编程技术网

C+中的模式匹配+; 我在C++中编写编译器,作为编译器,它需要大量的模式匹配和动态转换。在Rust、Haskell和OCaml等语言中,我可以轻松销毁类型,如: match node { Binary{ left, right, operator } => { .. } _ => { .. } } C++中我能做的最好的是: if (auto bin = dynamic_cast<Binary*>(node)) { ... } else if (...) { ... } if(auto bin=dynamic_cast(node)){…} 如果(…){…}

C+中的模式匹配+; 我在C++中编写编译器,作为编译器,它需要大量的模式匹配和动态转换。在Rust、Haskell和OCaml等语言中,我可以轻松销毁类型,如: match node { Binary{ left, right, operator } => { .. } _ => { .. } } C++中我能做的最好的是: if (auto bin = dynamic_cast<Binary*>(node)) { ... } else if (...) { ... } if(auto bin=dynamic_cast(node)){…} 如果(…){…},c++,pattern-matching,C++,Pattern Matching,如果你在场景中引入智能指针,这是非常有限和丑陋的。例如,如果我需要为某事匹配两件事: 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 y

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

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...
}
bool matched=false;
if(自动m1=动态施法(a)){
if(自动m2=动态施法(b)){
匹配=真;
}
}
如果(!匹配){
//这是因为C++不允许在条件内声明两个变量…
}
我知道Mach7库,但老实说,它看起来很糟糕,因为您需要为您的结构编写元数据(我也注意到它有很多bug和限制)


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

以下似乎是避免两个匹配的双if的一种方法,并且可以很容易地推广:

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)) {
模板结构castPairstruct:public std::pair{ 运算符bool(){return first&&second;} castPairstruct(t1a,t2b):std::pair(a,b){;} }; 模板浇注对结构浇注对(T1 a,T2 b){ 返回castPairstruct(a、b); } if(自动j=铸件对(动态铸件(a)、动态铸件(b)){
在编译器中,您可能会有一组明确的可能类型,那么在基类中存储一个
enum
值并打开该值如何?@Quentin这将涉及修改AST并将每个类型设置为其适当的值。这当然会更好,但仍然不是一个比较好的解决方案。没有模式匹配如果你需要模式匹配,为什么使用C++ C++?这是一种我非常满意的语言。我知道没有合适的模式匹配。你可能喜欢我的ACCU 2017对话:但是它只适用于不同类型。