C++Spec 1.0.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 void reset() noexcept { delivered = false; }
24 [[nodiscard]] constexpr bool has_result() const noexcept { return this->delivered; }
25};
26
33template <typename T>
34class Let : public LetBase {
35 using block_t = std::function<T()>;
36 std::optional<T> result;
37
38 block_t body;
39
40 void exec();
41
42 public:
43 explicit Let(block_t body) noexcept : LetBase(), body(body) {}
44
45 T* operator->() {
46 return std::addressof(value());
47 }
48
49 T& operator*() & { return value(); }
50 T& value() &;
51};
52
54template <typename T>
55void Let<T>::exec() {
56 if (!delivered) {
57 result = body();
58 delivered = true;
59 }
60}
61
66template <typename T>
67T& Let<T>::value() & {
68 exec();
69 return result.value();
70}
71
72} // namespace CppSpec
Base class for lets to abstract away the template arguments.
Definition let.hpp:16