1 /*
2  * Copyright (C) 2019 The Android Open Source Project
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 
17 #pragma once
18 
19 #include <memory>
20 
21 template<typename T>
makeSafeCallback(T * obj,std::function<void (T *)> f)22 std::function<void()> makeSafeCallback(T *obj, std::function<void(T *)> f) {
23     auto weak_me = std::weak_ptr<T>(obj->shared_from_this());
24     return [f, weak_me]{
25         auto me = weak_me.lock();
26         if (me) {
27             f(me.get());
28         }
29     };
30 }
31 
32 template<typename T, typename... Params>
makeSafeCallback(T * obj,void (T::* f)(const Params &...),const Params &...params)33 std::function<void()> makeSafeCallback(
34         T *obj, void (T::*f)(const Params&...), const Params&... params) {
35     return makeSafeCallback<T>(
36             obj,
37             [f, params...](T *me) {
38                 (me->*f)(params...);
39             });
40 }
41 
42 template<typename T, typename... Params>
makeSafeCallback(T * obj,void (T::* f)(Params...),const Params &...params)43 std::function<void()> makeSafeCallback(
44         T *obj, void (T::*f)(Params...), const Params&... params) {
45     return makeSafeCallback<T>(
46             obj,
47             [f, params...](T *me) {
48                 (me->*f)(params...);
49             });
50 }
51