CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
LazyConstructed.h
Go to the documentation of this file.
1 #ifndef CommonTools_Utils_LazyConstructed_h
2 #define CommonTools_Utils_LazyConstructed_h
3 // -*- C++ -*-
4 //
5 // Package: CommonTools/Utils
6 // Class : LazyConstructed
7 //
19 //
20 // Original Author: Jonas Rembser
21 // Created: Mon, 14 Aug 2020 16:05:45 GMT
22 //
23 //
24 #include <tuple>
25 #include <optional>
26 
27 template <class WrappedClass, class... Args>
29 public:
30  LazyConstructed(Args const&... args) : args_(args...) {}
31 
32  WrappedClass& value() {
33  if (!object_) {
34  evaluate();
35  }
36  return object_.value();
37  }
38 
39 private:
40  void evaluate() { evaluateImpl(std::make_index_sequence<sizeof...(Args)>{}); }
41 
42  template <std::size_t... ArgIndices>
43  void evaluateImpl(std::index_sequence<ArgIndices...>) {
44  object_ = WrappedClass(std::get<ArgIndices>(args_)...);
45  }
46 
47  std::optional<WrappedClass> object_ = std::nullopt;
48  std::tuple<Args const&...> args_;
49 };
50 
51 // helper function to create a LazyConstructed where the Args are deduced from the function argument types
52 template <class WrappedClass, class... Args>
53 auto makeLazy(Args&&... args) {
54  return LazyConstructed<WrappedClass, Args...>(std::forward<Args>(args)...);
55 }
56 
57 #endif
auto makeLazy(Args &&...args)
std::tuple< Args const &...> args_
std::optional< WrappedClass > object_
void evaluateImpl(std::index_sequence< ArgIndices...>)
WrappedClass & value()
LazyConstructed(Args const &...args)