title: Pattern matching in C++
body: <p>I'm writing a compiler in C++ and as any compiler, it requires an extreme amount of pattern matching and dynamic casts. In languages like Rust, Haskell, and OCaml I can destruct a type easily, like:</p>
  
  <pre><code>match node {
      Binary{ left, right, operator } =&gt; { .. }
      _ =&gt; { .. }
  }
  </code></pre>
  
  <p>In C++ the best I can do is:</p>
  
  <pre><code>if (auto bin = dynamic_cast&lt;Binary*&gt;(node)) { ... }
  else if (...) { ... }
  </code></pre>
  
  <p>Which is really limited and ugly if you introduce smart pointers into the scene. For example if I need to match 2 things for something:</p>
  
  <pre><code>bool matched = false;
  if (auto m1 = dynamic_cast&lt;Foo*&gt;(a)) {
      if (auto m2 = dynamic_cast&lt;Bar*&gt;(b)) {
          matched = true;
      }
  }
  if (!matched) {
      // This is because C++ does not allow you to declare two variables inside the condition...
  }
  </code></pre>
  
  <p>I know about the Mach7 library but to be honest it seems awful as you need to write metadata for your structures (also as I've noticed it has quite a lot of bugs and limitations).</p>
  
  <p>Is there a way to make these kind of matches more readable?</p>