parent
6870125249
commit
943f1b913b
@ -0,0 +1,45 @@
|
|||||||
|
// Copyright (C) 2024 Simon Quigley <tsimonq2@ubuntu.com>
|
||||||
|
//
|
||||||
|
// This program is free software: you can redistribute it and/or modify
|
||||||
|
// it under the terms of the GNU General Public License as published by
|
||||||
|
// the Free Software Foundation, either version 3 of the License, or
|
||||||
|
// (at your option) any later version.
|
||||||
|
//
|
||||||
|
// This program is distributed in the hope that it will be useful,
|
||||||
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
// GNU General Public License for more details.
|
||||||
|
//
|
||||||
|
// You should have received a copy of the GNU General Public License
|
||||||
|
// along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
#ifndef LAZY_OPTIONAL_H
|
||||||
|
#define LAZY_OPTIONAL_H
|
||||||
|
|
||||||
|
#include <optional>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
template <typename T, typename Loader>
|
||||||
|
class lazy_optional {
|
||||||
|
public:
|
||||||
|
lazy_optional(Loader loader) : loader_(std::move(loader)) {}
|
||||||
|
|
||||||
|
T& operator*() { load(); return *value_; }
|
||||||
|
const T& operator*() const { load(); return *value_; }
|
||||||
|
|
||||||
|
T* operator->() { load(); return &*value_; }
|
||||||
|
const T* operator->() const { load(); return &*value_; }
|
||||||
|
|
||||||
|
explicit operator bool() const { load(); return value_.has_value(); }
|
||||||
|
|
||||||
|
private:
|
||||||
|
mutable std::optional<T> value_;
|
||||||
|
[[no_unique_address]] Loader loader_;
|
||||||
|
|
||||||
|
// Removed constexpr
|
||||||
|
void load() const {
|
||||||
|
if (!value_) value_ = loader_();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif // LAZY_OPTIONAL_H
|
Loading…
Reference in new issue