1 /**
2 * Copyright 2019 Huawei Technologies Co., Ltd
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #ifndef MINDSPORE_CORE_UTILS_SIGNAL_H_
18 #define MINDSPORE_CORE_UTILS_SIGNAL_H_
19
20 #include <functional>
21 #include <memory>
22 #include <vector>
23 #include <utility>
24
25 namespace mindspore {
26 template <class Return, class Type, class... Args>
bind_member(Type * instance,Return (Type::* method)(Args...))27 std::function<Return(Args...)> bind_member(Type *instance, Return (Type::*method)(Args...)) {
28 return [=](Args &&... args) -> Return { return (instance->*method)(std::forward<Args>(args)...); };
29 }
30
31 template <class FuncType>
32 class Slot {
33 public:
Slot(const std::function<FuncType> & callback)34 explicit Slot(const std::function<FuncType> &callback) : callback(callback) {}
35
~Slot()36 ~Slot() {}
37
38 std::function<FuncType> callback = nullptr;
39 };
40
41 template <class FuncType>
42 class Signal {
43 public:
44 template <class... Args>
operator()45 void operator()(Args &&... args) {
46 for (auto &slot : slots_) {
47 if (slot->callback != nullptr) {
48 slot->callback(std::forward<Args>(args)...);
49 }
50 }
51 }
52
add_slot(const std::function<FuncType> & func)53 void add_slot(const std::function<FuncType> &func) {
54 auto slot = std::make_shared<Slot<FuncType>>(func);
55 slots_.push_back(slot);
56 }
57
58 // signal connect to a class member func
59 template <class InstanceType, class MemberFuncType>
connect(InstanceType instance,MemberFuncType func)60 void connect(InstanceType instance, MemberFuncType func) {
61 add_slot(bind_member(instance, func));
62 }
63
64 private:
65 std::vector<std::shared_ptr<Slot<FuncType>>> slots_;
66 };
67 } // namespace mindspore
68
69 #endif // MINDSPORE_CORE_UTILS_EVENT_H_
70