-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcall_chain.hpp
More file actions
72 lines (57 loc) · 2.05 KB
/
call_chain.hpp
File metadata and controls
72 lines (57 loc) · 2.05 KB
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
66
67
68
69
70
71
72
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2017 Dimitry Ishenko
// Contact: dimitry (dot) ishenko (at) (gee) mail (dot) com
//
// Distributed under the GNU GPL license. See the LICENSE.md file for details.
////////////////////////////////////////////////////////////////////////////////
#ifndef FIRMATA_CALL_CHAIN_HPP
#define FIRMATA_CALL_CHAIN_HPP
////////////////////////////////////////////////////////////////////////////////
#include <functional>
#include <map>
#include <tuple>
////////////////////////////////////////////////////////////////////////////////
namespace firmata
{
////////////////////////////////////////////////////////////////////////////////
// Alias for function
template<typename Fn>
using call = std::function<Fn>;
// Call id
using cid = std::tuple<unsigned, unsigned>;
////////////////////////////////////////////////////////////////////////////////
// Chain of functions
template<typename Fn>
struct call_chain
{
////////////////////
call_chain(unsigned token = 0) noexcept : token_(token), id_(0) { }
call_chain(const call_chain&) = delete;
call_chain(call_chain&&) noexcept = default;
call_chain& operator=(const call_chain&) = delete;
call_chain& operator=(call_chain&&) noexcept = default;
////////////////////
auto insert(Fn fn)
{
cid id(token_, id_++);
chain_.emplace(id, std::move(fn));
return id;
}
bool erase(cid id) { return chain_.erase(id); }
void clear() { chain_.clear(); }
auto empty() const noexcept { return chain_.empty(); }
auto size() const noexcept { return chain_.size(); }
template<typename... Args>
void operator()(Args&&... args)
{
for(auto const& fn : chain_) fn.second(std::forward<Args>(args)...);
}
private:
////////////////////
unsigned token_, id_;
std::map<cid, Fn> chain_;
};
////////////////////////////////////////////////////////////////////////////////
}
////////////////////////////////////////////////////////////////////////////////
#endif