manage_ptr.hpp 1016 Bytes
Newer Older
Paul's avatar
Paul committed
1
2
3
4
5
6
7
8
#ifndef RTG_GUARD_RTG_MANAGE_PTR_HPP
#define RTG_GUARD_RTG_MANAGE_PTR_HPP

#include <memory>
#include <type_traits>

namespace rtg {

Paul's avatar
Paul committed
9
template <class F, F f> // NOLINT
Paul's avatar
Paul committed
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
struct manage_deleter
{
    template <class T>
    void operator()(T* x) const
    {
        if(x != nullptr)
        {
            f(x);
        }
    }
};

struct null_deleter
{
    template <class T>
    void operator()(T*) const
    {
    }
};

template <class T, class F, F f>
using manage_ptr = std::unique_ptr<T, manage_deleter<F, f>>;

template <class T>
struct element_type
{
    using type = typename T::element_type;
};

template <class T>
Paul's avatar
Paul committed
40
41
using remove_ptr = typename std::
    conditional_t<std::is_pointer<T>{}, std::remove_pointer<T>, element_type<T>>::type;
Paul's avatar
Paul committed
42
43
44
45

template <class T>
using shared = std::shared_ptr<remove_ptr<T>>;

Paul's avatar
Paul committed
46
47
48
49
50
51
template<class T>
shared<T> share(T p)
{
    return shared<T>{std::move(p)};
}

Paul's avatar
Paul committed
52
53
} // namespace rtg

Paul's avatar
Paul committed
54
#define RTG_MANAGE_PTR(T, F) rtg::manage_ptr<std::remove_pointer_t<T>, decltype(&F), &F> // NOLINT
Paul's avatar
Paul committed
55
56

#endif