Nix  2.93.0-dev
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 <compare>
5#include <memory>
6#include <exception>
7#include <stdexcept>
8
9namespace nix {
10
15template<typename T>
16class ref
17{
18private:
19
20 std::shared_ptr<T> p;
21
22public:
23
24 ref(const ref<T> & r)
25 : p(r.p)
26 { }
27
28 explicit ref<T>(const std::shared_ptr<T> & p)
29 : p(p)
30 {
31 if (!p)
32 throw std::invalid_argument("null pointer cast to ref");
33 }
34
35 explicit ref<T>(T * p)
36 : p(p)
37 {
38 if (!p)
39 throw std::invalid_argument("null pointer cast to ref");
40 }
41
42 T* operator ->() const
43 {
44 return &*p;
45 }
46
47 T& operator *() const
48 {
49 return *p;
50 }
51
52 operator std::shared_ptr<T> () const
53 {
54 return p;
55 }
56
57 std::shared_ptr<T> get_ptr() const
58 {
59 return p;
60 }
61
62 template<typename T2>
63 ref<T2> cast() const
64 {
65 return ref<T2>(std::dynamic_pointer_cast<T2>(p));
66 }
67
68 template<typename T2>
69 std::shared_ptr<T2> dynamic_pointer_cast() const
70 {
71 return std::dynamic_pointer_cast<T2>(p);
72 }
73
74 template<typename T2>
75 operator ref<T2> () const
76 {
77 return ref<T2>((std::shared_ptr<T2>) p);
78 }
79
80 ref<T> & operator=(ref<T> const & rhs) = default;
81
82 bool operator == (const ref<T> & other) const
83 {
84 return p == other.p;
85 }
86
87 bool operator != (const ref<T> & other) const
88 {
89 return p != other.p;
90 }
91
92 bool operator < (const ref<T> & other) const
93 {
94 return p < other.p;
95 }
96
97private:
98
99 template<typename T2, typename... Args>
100 friend ref<T2>
101 make_ref(Args&&... args);
102
103};
104
105template<typename T, typename... Args>
106inline ref<T>
107make_ref(Args&&... args)
108{
109 auto p = std::make_shared<T>(std::forward<Args>(args)...);
110 return ref<T>(p);
111}
112
113}
Definition args.hh:31
Definition ref.hh:17