简体   繁体   中英

Convert antlrcpp::Any to std::string

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";
        }
    }
}

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
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM