From d63f5ce1cb86e69da28bd74b21e9452dbd88a38f Mon Sep 17 00:00:00 2001 From: Dan Goodliffe Date: Sun, 28 Feb 2021 15:42:39 +0000 Subject: Move utility to lib --- lib/collection.hpp | 71 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 lib/collection.hpp (limited to 'lib/collection.hpp') diff --git a/lib/collection.hpp b/lib/collection.hpp new file mode 100644 index 0000000..79c331a --- /dev/null +++ b/lib/collection.hpp @@ -0,0 +1,71 @@ +#ifndef COLLECTION_H +#define COLLECTION_H + +#include +#include +#include + +template class Collection { +public: + using Ptr = std::conditional_t, std::unique_ptr>; + using Objects = std::vector; + Objects objects; + + template + auto + create(Params &&... params) + { + if constexpr (shared) { + auto obj = std::make_shared(std::forward(params)...); + objects.emplace_back(obj); + return obj; + } + else { + return static_cast(objects.emplace_back(std::make_unique(std::forward(params)...)).get()); + } + } + + template + auto + apply(const M & m, Params &&... params) const + { + return std::count_if(objects.begin(), objects.end(), [&m, ¶ms...](auto && op) { + if (auto o = dynamic_cast(op.get())) { + std::invoke(m, o, std::forward(params)...); + return true; + } + return false; + }); + } + + template + auto + applyOne(const M & m, Params &&... params) const + { + return std::find_if(objects.begin(), objects.end(), [&m, ¶ms...](auto && op) { + if (auto o = dynamic_cast(op.get())) { + return std::invoke(m, o, std::forward(params)...); + } + return false; + }); + } + + template + void + removeAll() + { + objects.erase(std::remove_if(objects.begin(), objects.end(), + [](auto && op) { + return dynamic_cast(op.get()); + }), + objects.end()); + } + + auto + end() const + { + return objects.end(); + } +}; + +#endif -- cgit v1.2.3