Advertisement
jomega_ai

Untitled

Feb 11th, 2025
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.21 KB | Source Code | 0 0
  1. #include <iostream>
  2. #include <variant>
  3. #include <vector>
  4.  
  5. // Guitar class
  6. class Guitar {
  7. public:
  8.     void play() const {
  9.         std::cout << "Strumming the guitar!" << std::endl;
  10.     }
  11.     ~Guitar() {
  12.         std::cout << "Guitar destructor called." << std::endl;
  13.     }
  14. };
  15.  
  16. // Drums class
  17. class Drums {
  18. public:
  19.     void play() const {
  20.         std::cout << "Beating the drums!" << std::endl;
  21.     }
  22.     ~Drums() {
  23.         std::cout << "Drums destructor called." << std::endl;
  24.     }
  25. };
  26.  
  27. // Type-safe variant to hold multiple instrument types
  28. using Instrument = std::variant<Guitar, Drums>;
  29.  
  30. // Visitor to handle the play() function call
  31. struct PlayVisitor {
  32.     void operator()(const Guitar& guitar) const {
  33.         guitar.play();
  34.     }
  35.  
  36.     void operator()(const Drums& drums) const {
  37.         drums.play();
  38.     }
  39. };
  40.  
  41. int main() {
  42.     std::vector<Instrument> instruments;
  43.  
  44.     // Emplacing Guitar and Drums objects directly into the variant
  45.     instruments.emplace_back(Guitar());
  46.     instruments.emplace_back(Drums());
  47.  
  48.     // Demonstrating polymorphism using std::visit
  49.     for (const auto& instrument : instruments) {
  50.         std::visit(PlayVisitor{}, instrument);
  51.     }
  52.  
  53.     return 0;
  54. }
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement