Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #pragma once
- #include <functional>
- #include <optional>
- class OptionNone
- {
- };
- template <class T>
- class Option
- {
- // TODO
- };
- template <class T>
- class Option<T&>
- {
- private:
- T* ptr;
- public:
- Option(T& ref)
- : ptr{ &ref }
- {
- }
- Option(T* ptr)
- : ptr{ ptr }
- {
- }
- Option()
- : ptr{ nullptr }
- {
- }
- Option(const Option& that) = default;
- Option& operator=(const Option& that) = default;
- Option(Option&& that) = default;
- Option& operator=(Option&& that) = default;
- Option& operator=(const OptionNone&)
- {
- ptr = nullptr;
- return *this;
- }
- bool HasValue() const
- {
- return ptr;
- }
- T& Get()
- {
- return *ptr;
- }
- T& operator||(T& otherOption)
- {
- if (HasValue()) {
- return *ptr;
- } else {
- return otherOption;
- }
- }
- T& operator||(std::function<T()> computeOption)
- {
- if (HasValue()) {
- return *ptr;
- } else {
- return computeOption();
- }
- }
- };
- template <class T>
- static Option<T&> Some(T& ref)
- {
- return Option<T&>{ ref };
- }
- template <class T>
- static Option<T&> None()
- {
- return Option<T&>{};
- }
- static OptionNone None()
- {
- return OptionNone();
- }
- void f() {
- int a = 1;
- int b = 32;
- Option<int&> foo;
- foo = None();
- qInfo(foo.HasValue());
- qInfo(foo || a);
- qInfo(foo || [&]() { return b; });
- foo = Some(a);
- qInfo(foo.HasValue());
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement