It seems like the ANTLR4 C++ target's Any class has issues handling polymorphism with pointers. I am not quite sure how to put this into words, but I can provide an example of what I am observing. I would like to be able to pass around pointers of a Base class and call its member functions, as shown below:
#include "antlr4-runtime.h"
#include <string>
#include <iostream>
class Base {
public:
virtual std::string to_string() = 0;
};
class Derived : public Base {
public:
std::string to_string() {
return "foobar";
}
};
antlrcpp::Any test() {
return new Derived();
}
int main (void) {
auto value = test();
std::cout <<
value.as<Base*>()->to_string() << std::endl;
return 0;
}
However, the above code throws an exception `std::bad_cast` exception from within the `Any` class. I am not sure if this is by design or if there are some C++ issues preventing this from working... but can you advise on how to get this working? Any help here would be appreciated.
I can workaround this by explicitly stating `return (Base*) (new Derived());` in `test` but since forgetting this could blow up my code, I would much rather have the library take care of this for me.
As an aside, it would be very convenient if ANTLR4 had a way to specify the type of the abstract syntax tree to be something other than Any, because I would much rather use a pointer to my Base class for its type. Something like the Java interface, where we could specify ExampleBaseVisitor<Base*>.