Nix 2.93.3
Lix: A modern, delicious implementation of the Nix package manager; unstable internal interfaces
Loading...
Searching...
No Matches
ref.hh
Go to the documentation of this file.
1#pragma once
3
4#include <cassert>
5#include <compare>
6#include <memory>
7#include <exception>
8#include <optional>
9#include <stdexcept>
10
11namespace nix {
12
17template<typename T>
18class ref
19{
20private:
21
22 std::shared_ptr<T> p;
23
24 explicit ref<T>(const std::shared_ptr<T> & p)
25 : p(p)
26 {
27 assert(p);
28 }
29
30public:
31
32 ref(const ref<T> & r)
33 : p(r.p)
34 { }
35
36 static ref<T> unsafeFromPtr(const std::shared_ptr<T> & p)
37 {
38 return ref(p);
39 }
40
41 template<std::derived_from<std::enable_shared_from_this<T>> T2>
42 explicit ref(T2 & r) : p(r.shared_from_this())
43 {
44 }
45
46 T* operator ->() const
47 {
48 return &*p;
49 }
50
51 T& operator *() const
52 {
53 return *p;
54 }
55
56 operator std::shared_ptr<T> () const
57 {
58 return p;
59 }
60
61 std::shared_ptr<T> get_ptr() const
62 {
63 return p;
64 }
65
66 template<typename T2>
67 std::optional<ref<T2>> try_cast() const
68 {
69 if (auto d = std::dynamic_pointer_cast<T2>(p)) {
70 return ref<T2>::unsafeFromPtr(d);
71 } else {
72 return std::nullopt;
73 }
74 }
75
76 template<typename T2>
77 std::shared_ptr<T2> try_cast_shared() const
78 {
79 return std::dynamic_pointer_cast<T2>(p);
80 }
81
82 template<typename T2>
83 operator ref<T2> () const
84 {
85 return ref<T2>::unsafeFromPtr((std::shared_ptr<T2>) p);
86 }
87
88 ref<T> & operator=(ref<T> const & rhs) = default;
89
90 bool operator == (const ref<T> & other) const
91 {
92 return p == other.p;
93 }
94
95 bool operator != (const ref<T> & other) const
96 {
97 return p != other.p;
98 }
99
100 bool operator < (const ref<T> & other) const
101 {
102 return p < other.p;
103 }
104
105private:
106
107 template<typename T2, typename... Args>
108 friend ref<T2>
109 make_ref(Args&&... args);
110
111};
112
113template<typename T, typename... Args>
114inline ref<T>
115make_ref(Args&&... args)
116{
117 auto p = std::make_shared<T>(std::forward<Args>(args)...);
118 return ref<T>(p);
119}
120
121}
Definition args.hh:31
Definition ref.hh:19