我正在使用访问者模式编写从我的语法“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/