C++Spec 1.1.0
BDD testing for C++
Loading...
Searching...
No Matches
let.hpp
Go to the documentation of this file.
1
2#pragma once
3
4#include <functional>
5#include <optional>
6
7namespace CppSpec {
8
16class LetBase {
17 protected:
18 bool delivered{false};
19
20 public:
21 constexpr LetBase() noexcept = default;
22 LetBase(const LetBase& copy) = default;
23 LetBase(LetBase&& other) noexcept = default;
24 LetBase& operator=(const LetBase& copy) = default;
25 LetBase& operator=(LetBase&& other) noexcept = default;
27 virtual ~LetBase() = default;
28 void reset() noexcept { delivered = false; }
29 [[nodiscard]] constexpr bool has_result() const noexcept { return this->delivered; }
30};
31
38template <typename T>
39class Let : public LetBase {
40 using block_t = std::function<T()>;
41 std::optional<T> result;
42
43 block_t body;
44
45 void exec();
46
47 public:
48 explicit Let(block_t body) noexcept : LetBase(), body(body) {}
49
50 T* operator->() {
51 return std::addressof(value());
52 }
53
54 T& operator*() & { return value(); }
55 T& value() &;
56};
57
59template <typename T>
60void Let<T>::exec() {
61 if (!delivered) {
62 result = body();
63 delivered = true;
64 }
65}
66
71template <typename T>
72T& Let<T>::value() & {
73 exec();
74 return result.value();
75}
76
77} // namespace CppSpec
Base class for lets to abstract away the template arguments.
Definition let.hpp:16
virtual ~LetBase()=default
Virtual, as a Description owns its lets through std::unique_ptr<LetBase>.