Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2021-02-14 12:50:13

0001 #ifndef CommonTools_Utils_LazyConstructed_h
0002 #define CommonTools_Utils_LazyConstructed_h
0003 // -*- C++ -*-
0004 //
0005 // Package:     CommonTools/Utils
0006 // Class  :     LazyConstructed
0007 //
0008 /**\class LazyConstructed LazyConstructed.h "CommonTools/Utils/interface/LazyConstructed.h"
0009  Description: Wrapper around a class for lazy construction.
0010 
0011  Usage:
0012     // example: lazy SoA table
0013     auto object = makeLazy<edm::soa::EtaPhiTable>(trackCollection);
0014 
0015 Notes:
0016   * See similar class CommonTools/Utils/interface/LazyResult.h for implementation details.
0017 
0018 */
0019 //
0020 // Original Author:  Jonas Rembser
0021 //         Created:  Mon, 14 Aug 2020 16:05:45 GMT
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 // helper function to create a LazyConstructed where the Args are deduced from the function argument types
0052 template <class WrappedClass, class... Args>
0053 auto makeLazy(Args&&... args) {
0054   return LazyConstructed<WrappedClass, Args...>(std::forward<Args>(args)...);
0055 }
0056 
0057 #endif