Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <functional>
- #include <memory>
- #include <vector>
- // Type-erased Instrument class using std::function for polymorphic play
- class Instrument {
- public:
- // Constructor accepts any object with a play() function
- template <typename T>
- Instrument(T instrument)
- : play_func([instrument = std::make_shared<T>(std::move(instrument))]() { instrument->play(); })
- {}
- // Polymorphic play call
- void play() const {
- play_func();
- }
- private:
- std::function<void()> play_func; // Holds the type-erased play functionality
- };
- // Guitar class
- class Guitar {
- public:
- void play() const {
- std::cout << "Strumming the guitar!" << std::endl;
- }
- ~Guitar() {
- std::cout << "Guitar destructor called." << std::endl;
- }
- };
- // Drums class
- class Drums {
- public:
- void play() const {
- std::cout << "Beating the drums!" << std::endl;
- }
- ~Drums() {
- std::cout << "Drums destructor called." << std::endl;
- }
- };
- int main() {
- std::vector<Instrument> instruments;
- // Directly emplacing instruments into the vector
- instruments.emplace_back(Guitar());
- instruments.emplace_back(Drums());
- // Demonstrating polymorphism
- for (const auto& instrument : instruments) {
- instrument.play(); // Calls the correct play function
- }
- // Destructors will automatically be called when the objects go out of scope
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement