You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

signal.h 2.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. #ifndef MINDSPORE_CCSRC_UTILS_SIGNAL_H_
  17. #define MINDSPORE_CCSRC_UTILS_SIGNAL_H_
  18. #include <functional>
  19. #include <memory>
  20. #include <vector>
  21. #include <utility>
  22. namespace mindspore {
  23. template <class Return, class Type, class... Args>
  24. std::function<Return(Args...)> bind_member(Type *instance, Return (Type::*method)(Args...)) {
  25. return [=](Args &&... args) -> Return { return (instance->*method)(std::forward<Args>(args)...); };
  26. }
  27. template <class FuncType>
  28. class Slot {
  29. public:
  30. explicit Slot(const std::function<FuncType> &callback) : callback(callback) {}
  31. ~Slot() {}
  32. std::function<FuncType> callback = nullptr;
  33. };
  34. template <class FuncType>
  35. class Signal {
  36. public:
  37. template <class... Args>
  38. void operator()(Args &&... args) {
  39. for (auto &slot : slots_) {
  40. if (slot->callback != nullptr) {
  41. slot->callback(std::forward<Args>(args)...);
  42. }
  43. }
  44. }
  45. void add_slot(const std::function<FuncType> &func) {
  46. auto slot = std::make_shared<Slot<FuncType>>(func);
  47. slots_.push_back(slot);
  48. }
  49. // signal connect to a class member func
  50. template <class InstanceType, class MemberFuncType>
  51. void connect(InstanceType instance, MemberFuncType func) {
  52. add_slot(bind_member(instance, func));
  53. }
  54. private:
  55. std::vector<std::shared_ptr<Slot<FuncType>>> slots_;
  56. };
  57. } // namespace mindspore
  58. #endif // MINDSPORE_CCSRC_UTILS_EVENT_H_