Advertisement
jomega_ai

Untitled

Feb 11th, 2025
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.18 KB | Source Code | 0 0
  1. #include <iostream>
  2. #include <variant>
  3. #include <vector>
  4. #include <type_traits>
  5.  
  6. // Guitar class
  7. class Guitar {
  8. public:
  9.     void play() const {
  10.         std::cout << "Strumming the guitar!" << std::endl;
  11.     }
  12.     ~Guitar() {
  13.         std::cout << "Guitar destructor called." << std::endl;
  14.     }
  15. };
  16.  
  17. // Drums class
  18. class Drums {
  19. public:
  20.     void play() const {
  21.         std::cout << "Beating the drums!" << std::endl;
  22.     }
  23.     ~Drums() {
  24.         std::cout << "Drums destructor called." << std::endl;
  25.     }
  26. };
  27.  
  28. using Instrument = std::variant<Guitar, Drums>;
  29.  
  30. int main() {
  31.     std::vector<Instrument> instruments;
  32.     instruments.emplace_back(Guitar());
  33.     instruments.emplace_back(Drums());
  34.  
  35.     // C++20: Generic lambda with custom behavior based on type
  36.     for (const auto& instrument : instruments) {
  37.         std::visit([]<typename T>(const T& inst) {
  38.             if constexpr (std::is_same_v<T, Guitar>) {
  39.                 std::cout << "This is a guitar: ";
  40.             } else if constexpr (std::is_same_v<T, Drums>) {
  41.                 std::cout << "This is a drum set: ";
  42.             }
  43.             inst.play();
  44.         }, instrument);
  45.     }
  46.  
  47.     return 0;
  48. }
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement