DF-0
DF-0: Data processing Framework with Zero-overhead
Loading...
Searching...
No Matches
ref_or_owned.h
1/**************************************************************************/
2/* */
3/* DF-0: Data processing Framework with Zero-overhead */
4/* */
5/* Copyright (c) DF-0 Team https://github.com/df0-io/df0 */
6/* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-DF0-Commercial */
7/* */
8/**************************************************************************/
9
10#ifndef DF0_REF_OR_OWNED_H
11#define DF0_REF_OR_OWNED_H
12
13#include <memory>
14#include <type_traits>
15
16namespace df0
17{
18
19template<typename U, typename T>
20concept ref_or_owned_compatible = std::is_convertible_v<std::shared_ptr<std::remove_reference_t<U>>, std::shared_ptr<T>>;
21
30template <typename T>
31class ref_or_owned
32{
33 static_assert(!std::is_reference<T>::value, "ref_or_owned<T> cannot be instantiated with a reference type");
34 static_assert(!std::is_void<T>::value, "ref_or_owned<T> cannot be instantiated with void type");
35
36public:
37 ref_or_owned(ref_or_owned<T>&& other) noexcept
38 : v{other.to_shared_ptr()}
39 {}
40
41 ref_or_owned(const ref_or_owned<T>& other)
42 : v{other.to_shared_ptr()}
43 {}
44
46 ref_or_owned& operator=(const ref_or_owned<T>& other) {
47 v = other.v;
48 return *this;
49 }
50
52 ref_or_owned& operator=(ref_or_owned<T>&& other) noexcept {
53 v = std::move(other.v);
54 return *this;
55 }
56
64 template<ref_or_owned_compatible<T> U>
65 ref_or_owned(U& value)
66 : v{std::shared_ptr<T>{&value, [](auto*) {}}}
67 {}
68
76 template<ref_or_owned_compatible<T> U>
77 ref_or_owned(U&& value)
78 : v{std::make_shared<std::remove_reference_t<U>>(std::forward<U>(value))}
79 {}
80
81 template<ref_or_owned_compatible<T> U>
82 ref_or_owned(std::shared_ptr<U> ptr)
83 : v{ptr}
84 {}
85
91 const T& get() const {
92 return *v;
93 }
94
100 T& get() {
101 return *v;
102 }
103
104 std::shared_ptr<T> to_shared_ptr() const
105 {
106 return v;
107 }
108
109private:
110 std::shared_ptr<T> v;
111};
112
113} // namespace df0
114
115#endif //DF0_REF_OR_OWNED_H
A utility class that simplifies declaring function attributes that need to be stored without requirin...
T & get()
Returns a non-const reference to the stored object, regardless of whether it is stored as a reference...
ref_or_owned & operator=(const ref_or_owned< T > &other)
Copy assignment operator.
ref_or_owned(U &value)
Constructs a ref_or_owned object from a reference to an object.
const T & get() const
Returns a const reference to the stored object, regardless of whether it is stored as a reference or ...
ref_or_owned(U &&value)
Constructs a ref_or_owned object from a temporary object.
ref_or_owned & operator=(ref_or_owned< T > &&other) noexcept
Move assignment operator.