Advertisement
jomega_ai

Untitled

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