summaryrefslogtreecommitdiff
path: root/utility/collection.hpp
blob: 48eae0eca674a2ab5337be79d9eb5be16af9d384 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#ifndef COLLECTION_H
#define COLLECTION_H

#include <algorithm>
#include <memory>

template<typename Object> class Collection {
public:
	using Ptr = std::shared_ptr<Object>;
	using Objects = std::vector<Ptr>;
	Objects objects;

	template<typename T = Object, typename... Params>
	auto
	create(Params &&... params)
	{
		auto obj = std::make_shared<T>(std::forward<Params>(params)...);
		objects.emplace_back(obj);
		return obj;
	}

	template<typename T = Object, typename M = void, typename... Params>
	auto
	apply(const M & m, Params &&... params) const
	{
		return std::count_if(objects.begin(), objects.end(), [&m, &params...](auto && op) {
			if (auto o = dynamic_cast<T *>(op.get())) {
				std::invoke(m, o, std::forward<Params>(params)...);
				return true;
			}
			return false;
		});
	}

	template<typename T = Object, typename M = void, typename... Params>
	auto
	applyOne(const M & m, Params &&... params) const
	{
		return std::find_if(objects.begin(), objects.end(), [&m, &params...](auto && op) {
			if (auto o = dynamic_cast<T *>(op.get())) {
				return std::invoke(m, o, std::forward<Params>(params)...);
			}
			return false;
		});
	}

	template<typename T = Object>
	void
	removeAll()
	{
		objects.erase(std::remove_if(objects.begin(), objects.end(),
							  [](auto && op) {
								  return dynamic_cast<T *>(op.get());
							  }),
				objects.end());
	}

	auto
	end() const
	{
		return objects.end();
	}
};

#endif