将 antlrcpp::Any 转换为 std::string

Convert antlrcpp::Any to std::string

我正在使用访问者模式编写从语法 'qwerty' 到 C++ 目标的翻译器。由于基础 class QwertyParserBaseVisitor returns antlrcpp::Any 类型,派生 class QwertyParserBaseVisitorImpl 也是如此。但我想将翻译后的程序写入文件。如何将 antlrcpp::Any 转换为 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";
        }
    }
}

使用template<class U> StorageType<U>& as()。如果 U 是您在构造函数中传递的变量类型,则它可以正常工作。换句话说具体

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
}