c++ - 将 antlrcpp::Any 转换为 std::string

标签 c++ antlr antlr4

我正在使用访问者模式编写从我的语法“qwerty”到 C++ 目标的翻译器。由于基类 QwertyParserBaseVisitor 返回 antlrcpp::Any 类型,派生类 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
} 

关于c++ - 将 antlrcpp::Any 转换为 std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49940290/

相关文章:

c++ - 自定义内存分配器 : T* pointer, operator new 与 void pointer cast

java - 在 ANTLR 中,如何根据特定的低级规则解析流?

eclipse - 如何使用 ANTLR4 和 Maven 自动生成词法分析器+解析器?

c# - 将 LeftBracket 之后的所有内容解释为字符串,直到下一个 RightBracket

c++ - 如何在类模板之外定义类模板的构造函数模板?

c++ - 使用Cmake在Qt Creator中显示头文件

java - 将ANTLR生成的class文件合并成一个jar文件

java - 如何使用 ANTLR4 创建 AST?

java - 如何正确实现 ANTLR4 访问者

c++ - 命名空间的类析构函数