Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert antlrcpp::Any to std::string

Tags:

c++

antlr

antlr4

I am writing translator from my grammar 'qwerty' to C++ target using Visitor pattern. Since base class QwertyParserBaseVisitor returns antlrcpp::Any type, derived class QwertyParserBaseVisitorImpl so does. But I would like to write translated program to file. How can I convert antlrcpp::Any to std::string?

    ANTLRInputStream input(in_stream);
    QwertyLexer lexer(&input);
    CommonTokenStream tokens(&lexer);
    QwertyParser parser(&tokens);
    QwertyParserBaseVisitorImpl visitor;

    // returns "My translated to cpp code" wrapped with antlrcpp::Any;
    antlrcpp::Any translated = visitor.visit(parser.program()); 
    std::cout << translated;

namespace AntlrQwerty {
    class QwertyParserBaseVisitorImpl : public QwertyParserBaseVisitor {
        antlrcpp::Any 
        AntlrQwerty::QwertyParserBaseVisitorImpl::visitProgram 
        (AntlrQwerty::QwertyParser::ProgramContext *ctx) {
            return "My translated to cpp code";
        }
    }
}
like image 761
Марк Логвинович Avatar asked Nov 23 '25 06:11

Марк Логвинович


1 Answers

Use template<class U> StorageType<U>& as(). It works properly if U is an type of the variable you pass in constructor. In other words specifically

std::string hello("Hello, world");
antlrcpp::Any a(hello);
std::string string_value;
try {
    string_value = a.as<std::string>();
    std::cout << string_value << std::endl; // print "Hello, world"
} catch (std::bad_cast const& e){
    // failed to cast to string
} 
like image 77
Kaveh Vahedipour Avatar answered Nov 25 '25 20:11

Kaveh Vahedipour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!