1 /* 2 * Copyright (c) 2021 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef EVENT_BASE_UTILS_H 17 #define EVENT_BASE_UTILS_H 18 19 #include <cstdio> 20 #include <stdarg.h> 21 #include <iostream> 22 #include <unistd.h> 23 #include <memory> 24 25 class Event { 26 }; 27 28 template<typename T, typename... Args> 29 class EventBase { 30 typedef T (Event::*pMemFunc)(T arg, Args... args); 31 public: EventBase()32 EventBase() 33 { 34 m_obj = NULL; 35 m_func = NULL; 36 } 37 38 template<class _func_type> Associate(Event * obj,_func_type func)39 void Associate(Event* obj, _func_type func) 40 { 41 m_obj = obj; 42 m_func = static_cast<pMemFunc>(func); 43 } 44 template<class _func_type> DisAssociate(Event * obj,_func_type func)45 void DisAssociate(Event* obj, _func_type func) 46 { 47 if (obj != m_obj) { 48 return; 49 } 50 m_func = NULL; 51 } 52 SendEvent(T arg,Args...args)53 void SendEvent(T arg, Args... args) 54 { 55 (m_obj->*pMemFunc(m_func))(arg, args...); 56 } 57 58 private: 59 Event* m_obj; 60 pMemFunc m_func; 61 }; 62 63 /*************************event array**************************************/ 64 template<typename T, typename... Args> 65 class EventBaseArray { 66 #define EVENT_LIST_MAX_NUM (10) 67 typedef T (Event::*pMemFunc)(T arg, Args... args); 68 public: EventBaseArray()69 EventBaseArray() 70 { 71 m_totalFunc = 0; 72 m_obj = NULL; 73 for (int i = 0; i < EVENT_LIST_MAX_NUM; i++) { 74 m_func[i] = NULL; 75 } 76 } 77 78 template<class _func_type> Associate(Event * obj,_func_type func)79 void Associate(Event* obj, _func_type func) 80 { 81 m_obj = obj; 82 m_func[m_totalFunc] = static_cast<pMemFunc>(func); 83 m_totalFunc++; 84 } 85 86 template<class _func_type> DisAssociate(Event * obj,_func_type func)87 void DisAssociate(Event* obj, _func_type func) 88 { 89 if (obj != m_obj) { 90 return; 91 } 92 int i; 93 for (i = 0; i < m_totalFunc; i++) { 94 if (m_func[i] == func) { 95 break; 96 } 97 } 98 for (i = 0; i < m_totalFunc - 1; i++) { 99 m_func[i] = m_func[i + 1]; 100 } 101 102 m_func[i] = NULL; 103 m_totalFunc--; 104 } 105 SendEvent(T arg,Args...args)106 void SendEvent(T arg, Args... args) 107 { 108 for (int i = 0; i < m_totalFunc; i++) { 109 if (m_func[i] != NULL) { 110 ((m_obj->*pMemFunc(m_func[i])))(arg, args...); 111 } 112 } 113 } 114 115 private: 116 Event* m_obj; 117 pMemFunc m_func[EVENT_LIST_MAX_NUM]; 118 int m_totalFunc; 119 }; 120 #endif 121