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 FOUNDATION_ACE_FRAMEWORKS_BASE_UTILS_EVENT_CALLBACK_H 17 #define FOUNDATION_ACE_FRAMEWORKS_BASE_UTILS_EVENT_CALLBACK_H 18 19 #include <functional> 20 21 #include "base/utils/base_id.h" 22 #include "base/utils/macros.h" 23 24 namespace OHOS::Ace { 25 26 template<class> 27 class EventCallback; 28 29 template<class R, class... Args> 30 class ACE_FORCE_EXPORT EventCallback<R(Args...)> : public BaseId { 31 public: 32 using FunctionType = std::function<R(Args...)>; 33 EventCallback()34 EventCallback() : callback_(nullptr) {} EventCallback(FunctionType && callback)35 explicit EventCallback(FunctionType&& callback) : callback_(std::move(callback)) {} EventCallback(const FunctionType & callback)36 explicit EventCallback(const FunctionType& callback) : callback_(callback) {} 37 38 ~EventCallback() override = default; 39 40 // Notice: uses operator bool to judge its legitimacy. operator()41 R operator()(Args&&... args) const 42 { 43 return callback_(std::forward<Args>(args)...); 44 } 45 46 explicit operator bool() const 47 { 48 return callback_ != nullptr; 49 } 50 51 bool operator==(std::nullptr_t) const 52 { 53 return callback_ == nullptr; 54 } 55 56 bool operator!=(std::nullptr_t) const 57 { 58 return callback_ != nullptr; 59 } 60 61 bool operator==(const EventCallback& callback) const 62 { 63 return GetId() == callback.GetId(); 64 } 65 66 bool operator<(const EventCallback& callback) const 67 { 68 return GetId() < callback.GetId(); 69 } 70 GetCallback()71 const FunctionType& GetCallback() const 72 { 73 return callback_; 74 } 75 76 private: 77 FunctionType callback_; 78 }; 79 80 } // namespace OHOS::Ace 81 82 #endif // FOUNDATION_ACE_FRAMEWORKS_BASE_UTILS_EVENT_CALLBACK_H 83