C++中的模式匹配
Pattern matching in C++
我正在用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)) {
相关文章:
- 模式匹配文本并提取C++中的数据
- 如何在CLIPS中优化不同模板事实之间的模式匹配
- Flex Lexer 模式匹配句子分隔符/标点符号作为 URL 路径部分
- C++中的模式匹配
- 模式匹配函数的时间测量无法正常工作
- C++向量的模式匹配
- 从.cpp文件中提取与模式匹配的"if"块
- 在某些情况下,通配符模式匹配失败
- 如何使用C++模板魔术来对类型进行模式匹配
- 使用 std::regex_search 获取与模式匹配的所有文件和文件夹
- 在 c++-17 中特化的模式匹配中 lambda 的拆分函数签名
- C++;仅当用户输入与预设模式匹配时才接受用户输入
- 下一个最大的整数,有一些中间位与模式匹配?
- 模板模式匹配
- 用于多个级联字符串的同步模式匹配算法
- 使用C++功能在系统路径中进行模式匹配
- 使用[msys]bash删除所有名称与模式匹配的文件,而不考虑文件名字母大小写
- DNA模式匹配中最快的算法是什么
- 使用后缀数组和 LCP(-LR) 实现字符串模式匹配
- 找到与另一个二进制模式匹配的所有 2 位值,然后对它们求和