mirror of
https://codeberg.org/DawnMagnet/reflect-cpp
synced 2026-11-29 22:36:19 +08:00
This commit is contained in:
+52
-6
@@ -1,4 +1,4 @@
|
||||
# `rfl::Box` and `rfl::Ref`
|
||||
# `rfl::Box` and `rfl::Ref`
|
||||
|
||||
In previous sections, we have defined the `Person` class recursively:
|
||||
|
||||
@@ -76,11 +76,11 @@ struct DecisionTree {
|
||||
```
|
||||
|
||||
This will compile, but the design is less than ideal. We know for a fact that a `Node` must have
|
||||
exactly two subtrees. But this is not reflected in the type system. In this encoding, the fields
|
||||
exactly two subtrees. But this is not reflected in the type system. In this encoding, the fields
|
||||
"lesser" and "greater" are marked optional and you will have to check at runtime that they are indeed set.
|
||||
|
||||
But this violates the principles of reflection. Reflection is all about validating as much of our assumptions
|
||||
upfront as we possibly can. For a great theoretical discussion of this topic, check out
|
||||
upfront as we possibly can. For a great theoretical discussion of this topic, check out
|
||||
[Parse, don't validate](https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/)
|
||||
by Alexis King.
|
||||
|
||||
@@ -109,7 +109,7 @@ struct DecisionTree {
|
||||
|
||||
`rfl::Box` is a thin wrapper around `std::unique_ptr`, but it is guaranteed to **never be null** (unless you do something egregious such as trying to access it after calling `std::move`). It is a `std::unique_ptr` without the `nullptr`.
|
||||
|
||||
If you want to learn more about the evils of null references, check out the
|
||||
If you want to learn more about the evils of null references, check out the
|
||||
[Null References: The Billion Dollar Mistake](https://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare/)
|
||||
by Tony Hoare, who invented the concept in the first place.
|
||||
|
||||
@@ -145,10 +145,10 @@ auto ptr = std::make_unique<std::string>("Hello World!");
|
||||
const rfl::Result<rfl::Box<std::string>> box = rfl::make_box<std::string>(std::move(ptr));
|
||||
```
|
||||
|
||||
Note that `box` is wrapped in a `Result`. That is, because we cannot guarantee at compile time
|
||||
Note that `box` is wrapped in a `Result`. That is, because we cannot guarantee at compile time
|
||||
that `ptr` is not `nullptr`, therefore we need to account for that.
|
||||
|
||||
If you want to use reference-counted pointers, instead of unique pointers, you can use `rfl::Ref`.
|
||||
If you want to use reference-counted pointers, instead of unique pointers, you can use `rfl::Ref`.
|
||||
`rfl::Ref` is the same concept as `rfl::Box`, but using `std::shared_ptr` under-the-hood.
|
||||
|
||||
```cpp
|
||||
@@ -190,5 +190,51 @@ The resulting JSON string is identical:
|
||||
{"leafOrNode":{"type":"Node","criticalValue":10.0,"lesser":{"leafOrNode":{"type":"Leaf","value":3.0}},"greater":{"leafOrNode":{"type":"Leaf","value":5.0}}}}
|
||||
```
|
||||
|
||||
## Deep Copying
|
||||
|
||||
The default `rfl::Box` implementation behaves the same as `std::unique_ptr` in relation to copying, disabling the copy assignment operator and the copy constructor.
|
||||
|
||||
An opt-in box implementation, `rfl::CopyableBox`, bypasses the `std::unique_ptr` operators and allows copying by calling
|
||||
the contained type's copy constructor and copy assignment operator directly, but otherwise
|
||||
behaves the same as `rfl::Box`.
|
||||
|
||||
When using `rfl::CopyableBox`, `rfl::make_box<...>(...)` must be replaced with `rfl::make_copyable_box<...>(...)`.
|
||||
|
||||
This allows for deep-copying of arbitrary-complexity types that contain nested recursive elements:
|
||||
|
||||
```cpp
|
||||
struct DecisionTree {
|
||||
struct Leaf {
|
||||
using Tag = rfl::Literal<"Leaf">;
|
||||
double prediction;
|
||||
};
|
||||
|
||||
struct Node {
|
||||
using Tag = rfl::Literal<"Node">;
|
||||
rfl::Rename<"criticalValue", double> critical_value;
|
||||
rfl::CopyableBox<DecisionTree> lesser;
|
||||
rfl::CopyableBox<DecisionTree> greater;
|
||||
};
|
||||
|
||||
using LeafOrNode = rfl::TaggedUnion<"type", Leaf, Node>;
|
||||
|
||||
rfl::Field<"leafOrNode", LeafOrNode> leaf_or_node;
|
||||
};
|
||||
|
||||
|
||||
auto leaf1 = DecisionTree::Leaf{.value = 3.0};
|
||||
|
||||
auto leaf2 = DecisionTree::Leaf{.value = 5.0};
|
||||
|
||||
auto node =
|
||||
DecisionTree::Node{.critical_value = 10.0,
|
||||
.lesser = rfl::make_copyable_box<DecisionTree>(leaf1),
|
||||
.greater = rfl::make_copyable_box<DecisionTree>(leaf2)};
|
||||
|
||||
const DecisionTree tree{.leaf_or_node = std::move(node)};
|
||||
|
||||
auto different_leaf = DecisionTree::Leaf{.value = 1.0};
|
||||
DecisionTree copy = tree;
|
||||
|
||||
rfl::get<DecisionTree::Node>(copy.leaf_or_node.get().variant()).lesser = rfl::make_copyable_box<DecisionTree>(different_leaf);
|
||||
```
|
||||
|
||||
+48
-13
@@ -8,37 +8,55 @@
|
||||
|
||||
namespace rfl {
|
||||
|
||||
|
||||
enum class Copyability {
|
||||
COPYABLE,
|
||||
NON_COPYABLE
|
||||
};
|
||||
|
||||
/// The Box class behaves very similarly to the unique_ptr, but unlike the
|
||||
/// unique_ptr, it is 100% guaranteed to be filled at all times (unless the user
|
||||
/// tries to access it after calling std::move does something else that is
|
||||
/// clearly bad practice).
|
||||
template <class T>
|
||||
///
|
||||
/// By default Box behaves like a unique_ptr in relation to copying, but it can be
|
||||
/// configured to add copy constructor and assignment operators that call the
|
||||
/// same function of the contained type T.
|
||||
|
||||
template <class T, Copyability C = Copyability::NON_COPYABLE>
|
||||
class Box {
|
||||
public:
|
||||
/// The only way of creating new boxes is
|
||||
/// Box<T>::make(...).
|
||||
template <class... Args>
|
||||
static Box<T> make(Args&&... _args) {
|
||||
return Box<T>(std::make_unique<T>(std::forward<Args>(_args)...));
|
||||
static Box<T, C> make(Args&&... _args) {
|
||||
return Box<T, C>(std::make_unique<T>(std::forward<Args>(_args)...));
|
||||
}
|
||||
|
||||
/// You can generate them from unique_ptrs as well, in which case it will
|
||||
/// return an Error, if the unique_ptr is not set.
|
||||
static Result<Box<T>> make(std::unique_ptr<T>&& _ptr) {
|
||||
static Result<Box<T, C>> make(std::unique_ptr<T>&& _ptr) {
|
||||
if (!_ptr) {
|
||||
return error("std::unique_ptr was a nullptr.");
|
||||
}
|
||||
return Box<T>(std::move(_ptr));
|
||||
return Box<T, C>(std::move(_ptr));
|
||||
}
|
||||
|
||||
Box() : ptr_(std::make_unique<T>()) {}
|
||||
|
||||
Box(const Box<T>& _other) = delete;
|
||||
/// Copy constructor if copyable
|
||||
Box(const Box<T, C>& _other) requires (C == Copyability::COPYABLE)
|
||||
{
|
||||
ptr_ = std::make_unique<T>(*_other);
|
||||
}
|
||||
|
||||
Box(Box<T>&& _other) = default;
|
||||
/// Copy constructor if not copyable
|
||||
Box(const Box<T, C>& _other) requires (C == Copyability::NON_COPYABLE) = delete;
|
||||
|
||||
template <class U>
|
||||
Box(Box<U>&& _other) noexcept
|
||||
Box(Box<T, C>&& _other) = default;
|
||||
|
||||
template <class U, Copyability C2>
|
||||
Box(Box<U, C2>&& _other) noexcept
|
||||
: ptr_(std::forward<std::unique_ptr<U>>(_other.ptr())) {}
|
||||
|
||||
~Box() = default;
|
||||
@@ -46,15 +64,23 @@ class Box {
|
||||
/// Returns a pointer to the underlying object
|
||||
T* get() const { return ptr_.get(); }
|
||||
|
||||
/// Copy assignment operator
|
||||
Box<T>& operator=(const Box<T>& _other) = delete;
|
||||
/// Copy assignment operator if copyable
|
||||
Box<T, C>& operator=(const Box<T>& other) requires (C == Copyability::COPYABLE) {
|
||||
if(this != &other) {
|
||||
ptr_ = std::make_unique<T>(*other);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
/// Copy assignment operator if not copyable
|
||||
Box<T, C>& operator=(const Box<T>& _other) requires (C == Copyability::NON_COPYABLE) = delete;
|
||||
|
||||
/// Move assignment operator
|
||||
Box<T>& operator=(Box<T>&& _other) noexcept = default;
|
||||
Box<T, C>& operator=(Box<T, C>&& _other) noexcept = default;
|
||||
|
||||
/// Move assignment operator
|
||||
template <class U>
|
||||
Box<T>& operator=(Box<U>&& _other) noexcept {
|
||||
Box<T, C>& operator=(Box<U>&& _other) noexcept {
|
||||
ptr_ = std::forward<std::unique_ptr<U>>(_other.ptr());
|
||||
return *this;
|
||||
}
|
||||
@@ -92,6 +118,15 @@ auto make_box(Args&&... _args) {
|
||||
return Box<T>::make(std::forward<Args>(_args)...);
|
||||
}
|
||||
|
||||
/// Template specialization for a box that is copyable.
|
||||
template<typename T>
|
||||
using CopyableBox = Box<T, Copyability::COPYABLE>;
|
||||
|
||||
template <class T, class... Args>
|
||||
auto make_copyable_box(Args&&... _args) {
|
||||
return CopyableBox<T>::make(std::forward<Args>(_args)...);
|
||||
}
|
||||
|
||||
template <class T1, class T2>
|
||||
inline auto operator<=>(const Box<T1>& _b1, const Box<T2>& _b2) {
|
||||
return _b1.ptr() <=> _b2.ptr();
|
||||
|
||||
@@ -12,19 +12,19 @@
|
||||
namespace rfl {
|
||||
namespace parsing {
|
||||
|
||||
template <class R, class W, class T, class ProcessorsType>
|
||||
requires AreReaderAndWriter<R, W, Box<T>>
|
||||
struct Parser<R, W, Box<T>, ProcessorsType> {
|
||||
template <class R, class W, class T, Copyability C, class ProcessorsType>
|
||||
requires AreReaderAndWriter<R, W, Box<T, C>>
|
||||
struct Parser<R, W, Box<T, C>, ProcessorsType> {
|
||||
using InputVarType = typename R::InputVarType;
|
||||
|
||||
static Result<Box<T>> read(const R& _r, const InputVarType& _var) noexcept {
|
||||
const auto to_box = [](auto&& _t) { return Box<T>::make(std::move(_t)); };
|
||||
static Result<Box<T, C>> read(const R& _r, const InputVarType& _var) noexcept {
|
||||
const auto to_box = [](auto&& _t) { return Box<T, C>::make(std::move(_t)); };
|
||||
return Parser<R, W, std::remove_cvref_t<T>, ProcessorsType>::read(_r, _var)
|
||||
.transform(to_box);
|
||||
}
|
||||
|
||||
template <class P>
|
||||
static void write(const W& _w, const Box<T>& _box,
|
||||
static void write(const W& _w, const Box<T, C>& _box,
|
||||
const P& _parent) noexcept {
|
||||
Parser<R, W, std::remove_cvref_t<T>, ProcessorsType>::write(_w, *_box,
|
||||
_parent);
|
||||
|
||||
@@ -26,6 +26,7 @@ struct DecisionTree {
|
||||
rfl::Field<"leafOrNode", LeafOrNode> leaf_or_node;
|
||||
};
|
||||
|
||||
|
||||
TEST(generic, test_box) {
|
||||
auto leaf1 = DecisionTree::Leaf{.value = 3.0};
|
||||
|
||||
@@ -42,3 +43,49 @@ TEST(generic, test_box) {
|
||||
|
||||
}
|
||||
} // namespace test_box
|
||||
|
||||
|
||||
namespace test_copyable_box
|
||||
{
|
||||
struct DecisionTree {
|
||||
struct Leaf {
|
||||
using Tag = rfl::Literal<"Leaf">;
|
||||
double value;
|
||||
};
|
||||
|
||||
struct Node {
|
||||
using Tag = rfl::Literal<"Node">;
|
||||
rfl::Rename<"criticalValue", double> critical_value;
|
||||
rfl::CopyableBox<DecisionTree> lesser;
|
||||
rfl::CopyableBox<DecisionTree> greater;
|
||||
};
|
||||
|
||||
using LeafOrNode = rfl::TaggedUnion<"type", Leaf, Node>;
|
||||
|
||||
rfl::Field<"leafOrNode", LeafOrNode> leaf_or_node;
|
||||
};
|
||||
TEST(generic, copyable_box) {
|
||||
auto leaf1 = DecisionTree::Leaf{.value = 3.0};
|
||||
|
||||
auto leaf2 = DecisionTree::Leaf{.value = 5.0};
|
||||
|
||||
auto node = DecisionTree::Node{
|
||||
.critical_value = 10.0,
|
||||
.lesser = rfl::make_box<DecisionTree>(DecisionTree{leaf1}),
|
||||
.greater = rfl::make_box<DecisionTree>(DecisionTree{leaf2})};
|
||||
|
||||
const DecisionTree tree1{.leaf_or_node = std::move(node)};
|
||||
|
||||
write_and_read(tree1);
|
||||
|
||||
const DecisionTree tree2 = tree1;
|
||||
|
||||
auto lesser_leaf_tree2 = rfl::get<DecisionTree::Leaf>(rfl::get<DecisionTree::Node>(tree2.leaf_or_node.get().variant()).lesser.get()->leaf_or_node.get().variant());
|
||||
lesser_leaf_tree2.value = 1.0;
|
||||
|
||||
|
||||
auto lesser_leaf_tree1 = rfl::get<DecisionTree::Leaf>(rfl::get<DecisionTree::Node>(tree1.leaf_or_node.get().variant()).lesser.get()->leaf_or_node.get().variant());
|
||||
EXPECT_NE(lesser_leaf_tree1.value, lesser_leaf_tree2.value);
|
||||
|
||||
}
|
||||
} // namespace test_copyable_box
|
||||
|
||||
Reference in New Issue
Block a user