File indexing completed on 2024-04-06 12:01:18
0001 #ifndef CommonTools_Utils_LazyConstructed_h
0002 #define CommonTools_Utils_LazyConstructed_h
0003
0004
0005
0006
0007
0008
0009
0010
0011
0012
0013
0014
0015
0016
0017
0018
0019
0020
0021
0022
0023
0024 #include <tuple>
0025 #include <optional>
0026
0027 template <class WrappedClass, class... Args>
0028 class LazyConstructed {
0029 public:
0030 LazyConstructed(Args const&... args) : args_(args...) {}
0031
0032 WrappedClass& value() {
0033 if (!object_) {
0034 evaluate();
0035 }
0036 return object_.value();
0037 }
0038
0039 private:
0040 void evaluate() { evaluateImpl(std::make_index_sequence<sizeof...(Args)>{}); }
0041
0042 template <std::size_t... ArgIndices>
0043 void evaluateImpl(std::index_sequence<ArgIndices...>) {
0044 object_ = WrappedClass(std::get<ArgIndices>(args_)...);
0045 }
0046
0047 std::optional<WrappedClass> object_ = std::nullopt;
0048 std::tuple<Args const&...> args_;
0049 };
0050
0051
0052 template <class WrappedClass, class... Args>
0053 auto makeLazy(Args&&... args) {
0054 return LazyConstructed<WrappedClass, Args...>(std::forward<Args>(args)...);
0055 }
0056
0057 #endif