changeset 1831:498ed1e86f92

Add GenericCommand
author Chris Cannam
date Fri, 27 Mar 2020 10:06:03 +0000
parents a4dce53b3353
children 7c92c644db20
files base/Command.h
diffstat 1 files changed, 51 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/base/Command.h	Fri Mar 06 12:53:18 2020 +0000
+++ b/base/Command.h	Fri Mar 27 10:06:03 2020 +0000
@@ -19,6 +19,7 @@
 #include <QObject>
 #include <QString>
 #include <vector>
+#include <functional>
 
 #include "Debug.h"
 
@@ -32,6 +33,56 @@
     virtual QString getName() const = 0;
 };
 
+/** 
+ * GenericCommand is a Command that can be constructed directly using
+ * lambdas, without having to create a subclass. Best for commands
+ * invoked only in a single place, and where little state is involved.
+ */
+class GenericCommand : public Command
+{
+public:
+    GenericCommand(QString name,
+                   std::function<void()> execute,
+                   std::function<void()> unexecute) :
+        m_name(name),
+        m_execute(execute),
+        m_unexecute(unexecute),
+        m_onDelete([] {}) {
+    }
+
+    GenericCommand(QString name,
+                   std::function<void()> execute,
+                   std::function<void()> unexecute,
+                   std::function<void()> onDelete) :
+        m_name(name),
+        m_execute(execute),
+        m_unexecute(unexecute),
+        m_onDelete(onDelete) {
+    }
+    
+    virtual ~GenericCommand() {
+        m_onDelete();
+    }
+
+    QString getName() const override {
+        return m_name;
+    }
+    
+    void execute() override {
+        m_execute();
+    }
+
+    void unexecute() override {
+        m_unexecute();
+    }
+
+private:
+    QString m_name;
+    std::function<void()> m_execute;
+    std::function<void()> m_unexecute;
+    std::function<void()> m_onDelete;
+};    
+
 class MacroCommand : public Command
 {
 public: