File: event.h

package info (click to toggle)
freespace2 24.2.0%2Brepack-1
  • links: PTS, VCS
  • area: non-free
  • in suites: forky, sid
  • size: 43,716 kB
  • sloc: cpp: 595,001; ansic: 21,741; python: 1,174; sh: 457; makefile: 248; xml: 181
file content (47 lines) | stat: -rw-r--r-- 1,046 bytes parent folder | download | duplicates (2)
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
#pragma once

#include "globalincs/pstypes.h"

#include <functional>

namespace util {

template <typename Ret, typename... Args>
class event final {
  public:
	using callback_type = std::function<Ret(Args...)>;

	event()  = default;
	~event() = default;

	void add(callback_type func) { _listeners.push_back(func); }

	void clear() { _listeners.clear(); }

	// This variant is used if the listeners return no values
	template <typename Dummy = void>
	inline typename std::enable_if<std::is_same<Ret, void>::value, Dummy>::type operator()(Args... args) const
	{
		for (const auto& l : _listeners) {
			l(args...);
		}
	}

	// In this case we collect the return values and return them to the caller
	template <typename Dummy = SCP_vector<Ret>>
	inline typename std::enable_if<!std::is_same<Ret, void>::value, Dummy>::type operator()(Args... args) const
	{
		SCP_vector<Ret> vals;

		for (const auto& l : _listeners) {
			vals.push_back(l(args...));
		}

		return vals;
	}

  private:
	SCP_vector<callback_type> _listeners;
};

} // namespace util