# HG changeset patch # User Chris Cannam # Date 1585303563 0 # Node ID 498ed1e86f9228a09e2057598378dfd43c792b7d # Parent a4dce53b33531f99b1202e9837694ab2ef4fffe6 Add GenericCommand diff -r a4dce53b3353 -r 498ed1e86f92 base/Command.h --- 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 #include #include +#include #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 execute, + std::function unexecute) : + m_name(name), + m_execute(execute), + m_unexecute(unexecute), + m_onDelete([] {}) { + } + + GenericCommand(QString name, + std::function execute, + std::function unexecute, + std::function 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 m_execute; + std::function m_unexecute; + std::function m_onDelete; +}; + class MacroCommand : public Command { public: