title: Retrieving Base class from antlrcpp::Any
body: <p>I'm currently porting over some code from the C# version of ANTLR4 to the C++ target and I'm currently running into some issues. The way I built my AST in C# was to create a base class (let's call it Base) and derived classes (let's called it Derived) with virtual functions which I can use to implement said classes. </p>
  
  <p>However trying to convert this code to C++, I keep getting bad_cast exceptions
  I've narrowed it down to antlrcpp::Any not correctly casting a derived class into its base class. For example:
  </p>
  
  <pre><code>class Base {
  public:
      virtual std::string ToString() const { return "Base\n"; }
  };
  
  class Derived : public Base {
  public:
      std::string ToString() const override { return "Derived\n"; }
  };
  
  int main() {
      Derived value;
      std::cout &lt;&lt; value.ToString(); //Obviously prints out Derived
      Base&amp; base_value = value;
      std::cout &lt;&lt; base_value.ToString(); //Still works exactly as expected and prints Derived
  
      auto any = antlrcpp::Any(value);
      auto derived = any.as&lt;Base&gt;(); //internally uses a dynamic_cast and throws a bad_cast 
      std::cout &lt;&lt; derived.ToString(); //never gets to here
  }
  </code></pre>
  
  <p>I initially thought it was maybe because it only worked with pointers, however
  </p>
  
  <pre><code>auto any = antlrcpp::Any(new Derived());
  std::cout &lt;&lt; any.as&lt;Base*&gt;()-&gt;ToString(); //throws bad_cast
  </code></pre>
  
  <p>I changed the <code>dynamic_cast</code> into a <code>static_cast</code> inside the header and it will cast, however it prints out "Base". And a C-style casting outright causes a crash when any data members get accessed.</p>
  
  <p>How exactly do I use <code>antlrcpp::Any</code> to get a Base class? Is there anything obvious I'm missing?</p>
  
  <p>And if this isn't possible, how exactly do I work around this? There's the .is() method, however there's many cases where checking to see the return value of visitor is of a certain type is just not feasible (such as with expressions, there can be 30-40 operators).</p>