Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <functional>
- #include <memory>
- #include <vector>
- // Type-erased wrapper for runtime polymorphism
- class Instrument {
- public:
- // Constructor accepts any callable (like lambda) for playing
- template <typename T>
- Instrument(T instrument)
- : play_func([instrument]() mutable { instrument.play(); }),
- destructor_func([instrument]() mutable { instrument.~T(); })
- {}
- // Polymorphic play call
- void play() const {
- play_func();
- }
- // Destructor trigger to clean up any type properly
- ~Instrument() {
- destructor_func();
- }
- private:
- std::function<void()> play_func;
- std::function<void()> destructor_func;
- };
- // Guitar class without inheritance
- class Guitar {
- public:
- void play() {
- std::cout << "Strumming the guitar!" << std::endl;
- }
- ~Guitar() {
- std::cout << "Guitar destructor called." << std::endl;
- }
- };
- // Drums class without inheritance
- class Drums {
- public:
- void play() {
- std::cout << "Beating the drums!" << std::endl;
- }
- ~Drums() {
- std::cout << "Drums destructor called." << std::endl;
- }
- };
- int main() {
- std::vector<std::unique_ptr<Instrument>> instruments;
- // Emplacing objects directly into the type-erased wrapper
- instruments.emplace_back(std::make_unique<Instrument>(Guitar()));
- instruments.emplace_back(std::make_unique<Instrument>(Drums()));
- // Demonstrating polymorphism
- for (const auto& instrument : instruments) {
- instrument->play(); // Calls the correct play function based on the object
- }
- // Destructors will be called automatically when the unique_ptr goes out of scope
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement