#include#include struct MyVisitor : public boost::static_visitor { int operator()(int i) const { return i; } int operator()(std::string const& str) const { return str.length(); } }; int main() { boost::variant v("hello"); int result = boost::apply_visitor(MyVisitor(), v); std::cout << "Result: " << result << '\n'; return 0; }
#includeDescription: This example uses the LLVM library to define a visitor for the Value hierarchy in the LLVM IR. The MyVisitor struct defines two methods that handle the Constant and Instruction subclasses of Value. The main function creates a ConstantInt and a BinaryOperator Instruction and applies the visitor to each of them using the visit method.#include #include #include #include struct MyVisitor : public llvm::ValueVisitor { void visitConstant(llvm::Constant* C) { std::cout << "Constant\n"; } void visitInstruction(llvm::Instruction& I) { std::cout << "Instruction\n"; } }; int main() { llvm::Constant* c = llvm::ConstantInt::get(llvm::Type::getInt32Ty(llvm::getGlobalContext()), 42); llvm::Instruction* i = llvm::BinaryOperator::Create(llvm::Instruction::Add, llvm::ConstantInt::get(llvm::Type::getInt32Ty(llvm::getGlobalContext()), 5), llvm::ConstantInt::get(llvm::Type::getInt32Ty(llvm::getGlobalContext()), 7)); MyVisitor visitor; visitor.visit(c); visitor.visit(*i); return 0; }