gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:42:26 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com