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 #ifndef MULTIMEDIA_TEMPLATES_H
16 #define MULTIMEDIA_TEMPLATES_H
17 
18 #include <cstdint>
19 #include <memory>
20 #include <utility>
21 
22 namespace OHOS {
23 namespace MultiMedia {
24 /* call a function when this goes out of scope. The template uses two
25  * parameters, the object, and a function that is to be called in the destructor
26  */
27 template<typename T>
28 using remove_pointer_t = typename std::remove_pointer<T>::type;
29 
30 template<typename T, T *P>
31 struct FunctionWrapper {
32     template<typename... Args>
33     __attribute__((no_sanitize("cfi"))) auto operator()(Args &&... args)
34         const -> decltype(P(std::forward<Args>(args)...))
35     {
36         return P(std::forward<Args>(args)...);
37     }
38 };
39 
40 template<typename T, void (*P)(T *)>
41 class TAutoCallProc : public std::unique_ptr<T, FunctionWrapper<remove_pointer_t<decltype(P)>, P>> {
42 public:
TAutoCallProc(T * obj)43     explicit TAutoCallProc(T *obj) : std::unique_ptr<T, FunctionWrapper<remove_pointer_t<decltype(P)>, P>>(obj)
44     {}
45 
46     operator T *() const
47     {
48         return this->get();
49     }
50     ~TAutoCallProc() = default;
51 };
52 }  // namespace MultiMedia
53 }  // namespace OHOS
54 #endif  // MULTIMEDIA_TEMPLATES_H
55