1 // Copyright 2014 The Android Open Source Project
3 // This software is licensed under the terms of the GNU General Public
4 // License version 2, as published by the Free Software Foundation, and
5 // may be copied, distributed, and modified under those terms.
7 // This program is distributed in the hope that it will be useful,
8 // but WITHOUT ANY WARRANTY; without even the implied warranty of
9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 // GNU General Public License for more details.
14 #include "anbox/common/type_traits.h"
17 #include <type_traits>
27 void operator()(T ptr) const {
34 explicit FuncDelete(Func f = {}) : mF(f) {}
36 FuncDelete(const FuncDelete& other) = default;
37 FuncDelete(FuncDelete&& other) = default;
38 FuncDelete& operator=(const FuncDelete& other) = default;
39 FuncDelete& operator=(FuncDelete&& other) = default;
41 // To be able to copy/move from all compatible template instantiations.
43 friend struct FuncDelete;
45 // Template constructors and move assignment from compatible instantiations.
47 FuncDelete(const FuncDelete<U>& other) : mF(other.mF) {}
49 FuncDelete(FuncDelete<U>&& other) : mF(std::move(other.mF)) {}
51 FuncDelete& operator=(const FuncDelete<U>& other) {
56 FuncDelete& operator=(FuncDelete<U>&& other) {
57 mF = std::move(other.mF);
61 // This is the actual deleter call.
63 void operator()(T t) const {
71 template <class T, class Deleter = std::default_delete<T>>
72 using ScopedPtr = std::unique_ptr<T, Deleter>;
75 using ScopedCPtr = std::unique_ptr<T, FreeDelete>;
77 template <class T, class Func>
78 using ScopedCustomPtr = std::unique_ptr<T, FuncDelete<Func>>;
80 // A factory function that creates a scoped pointer with |deleter|
81 // function used as a deleter - it is called at the scope exit.
82 // Note: enable_if<> limits the scope of allowed arguments to pointers and
83 // std::nullptr_t (to allow makeCustomScopedPtr(nullptr, ...) calls).
86 class = enable_if_c<std::is_same<T, std::nullptr_t>::value ||
87 std::is_pointer<T>::value>>
89 typename std::decay<typename std::remove_pointer<T>::type>::type,
90 typename std::decay<Func>::type>
91 makeCustomScopedPtr(T data, Func deleter) {
92 return ScopedCustomPtr<
93 typename std::decay<typename std::remove_pointer<T>::type>::type,
94 typename std::decay<Func>::type>(
95 data, FuncDelete<typename std::decay<Func>::type>(deleter));