1 /* 2 * Copyright (c) 2023 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 RS_CORE_PIPELINE_RCD_ANY_H 17 #define RS_CORE_PIPELINE_RCD_ANY_H 18 #include <functional> 19 #include <mutex> 20 #include <thread> 21 #include <memory> 22 #include <iostream> 23 24 struct RsAny { RsAnyRsAny25 RsAny(void) {} RsAnyRsAny26 RsAny(const RsAny &that) : m_ptr(that.Clone()) {} RsAnyRsAny27 RsAny(RsAny &&that) : m_ptr(std::move(that.m_ptr)) {} 28 29 template<typename U, class = typename std::enable_if< RsAnyRsAny30 !std::is_same<typename std::decay<U>::type, RsAny>::value, U>::type> RsAny(U &&value) : m_ptr( 31 new Derived<typename std::decay<U>::type>(std::forward<U>(value))) {} 32 IsNULLRsAny33 bool IsNULL() const { return !bool(m_ptr); } 34 35 template<class U> anyCastRsAny36 U& anyCast() 37 { 38 auto derived = reinterpret_cast<Derived<U>*>(m_ptr.get()); 39 return derived->m_value; 40 } 41 42 template<typename... Args> SendRsAny43 void Send(Args... args) 44 { 45 std::lock_guard<std::mutex> lock(m_mutex); 46 auto f = anyCast<std::function<void(Args...)>>(); 47 f(args...); 48 } 49 50 RsAny& operator=(const RsAny &a) 51 { 52 if (m_ptr == a.m_ptr) { 53 return *this; 54 } 55 m_ptr = a.Clone(); 56 return *this; 57 } 58 59 private: 60 std::mutex m_mutex; 61 struct Base; 62 using BaseUPtr = std::unique_ptr<Base>; 63 struct Base { ~BaseRsAny::Base64 virtual ~Base() {} 65 virtual BaseUPtr Clone() const = 0; 66 }; 67 68 template<typename T> 69 struct Derived : Base { 70 template<typename U> DerivedRsAny::Derived71 Derived(U&& value) : m_value(std::forward<U>(value)) {} 72 CloneRsAny::Derived73 BaseUPtr Clone() const 74 { 75 return BaseUPtr(new Derived<T>(m_value)); 76 } 77 78 T m_value; 79 }; 80 81 BaseUPtr m_ptr; 82 83 public: CloneRsAny84 BaseUPtr Clone() const 85 { 86 if (m_ptr != nullptr) { 87 return m_ptr->Clone(); 88 } 89 return nullptr; 90 } 91 }; 92 #endif