Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <variant>
- #include <vector>
- // Guitar class
- class Guitar {
- public:
- void play() const {
- std::cout << "Strumming the guitar!" << std::endl;
- }
- ~Guitar() {
- std::cout << "Guitar destructor called." << std::endl;
- }
- };
- // Drums class
- class Drums {
- public:
- void play() const {
- std::cout << "Beating the drums!" << std::endl;
- }
- ~Drums() {
- std::cout << "Drums destructor called." << std::endl;
- }
- };
- // Type-safe variant to hold multiple instrument types
- using Instrument = std::variant<Guitar, Drums>;
- // Visitor to handle the play() function call
- struct PlayVisitor {
- void operator()(const Guitar& guitar) const {
- guitar.play();
- }
- void operator()(const Drums& drums) const {
- drums.play();
- }
- };
- int main() {
- std::vector<Instrument> instruments;
- // Emplacing Guitar and Drums objects directly into the variant
- instruments.emplace_back(Guitar());
- instruments.emplace_back(Drums());
- // Demonstrating polymorphism using std::visit
- for (const auto& instrument : instruments) {
- std::visit(PlayVisitor{}, instrument);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement