Advertisement
jomega_ai

Untitled

Feb 11th, 2025
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.48 KB | Source Code | 0 0
  1. #include <iostream>
  2. #include <functional>
  3. #include <memory>
  4. #include <vector>
  5.  
  6. // Type-erased Instrument class using std::function for polymorphic play
  7. class Instrument {
  8. public:
  9.     // Constructor accepts any object with a play() function
  10.     template <typename T>
  11.     Instrument(T instrument)
  12.         : play_func([instrument = std::make_shared<T>(std::move(instrument))]() { instrument->play(); })
  13.     {}
  14.  
  15.     // Polymorphic play call
  16.     void play() const {
  17.         play_func();
  18.     }
  19.  
  20. private:
  21.     std::function<void()> play_func;  // Holds the type-erased play functionality
  22. };
  23.  
  24. // Guitar class
  25. class Guitar {
  26. public:
  27.     void play() const {
  28.         std::cout << "Strumming the guitar!" << std::endl;
  29.     }
  30.     ~Guitar() {
  31.         std::cout << "Guitar destructor called." << std::endl;
  32.     }
  33. };
  34.  
  35. // Drums class
  36. class Drums {
  37. public:
  38.     void play() const {
  39.         std::cout << "Beating the drums!" << std::endl;
  40.     }
  41.     ~Drums() {
  42.         std::cout << "Drums destructor called." << std::endl;
  43.     }
  44. };
  45.  
  46. int main() {
  47.     std::vector<Instrument> instruments;
  48.  
  49.     // Directly emplacing instruments into the vector
  50.     instruments.emplace_back(Guitar());
  51.     instruments.emplace_back(Drums());
  52.  
  53.     // Demonstrating polymorphism
  54.     for (const auto& instrument : instruments) {
  55.         instrument.play();  // Calls the correct play function
  56.     }
  57.  
  58.     // Destructors will automatically be called when the objects go out of scope
  59.     return 0;
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement