File indexing completed on 2024-05-12 16:59:21

0001 /*
0002  *   SPDX-FileCopyrightText: 2015-2016 Ivan Cukic <ivan.cukic@kde.org>
0003  *
0004  *   SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
0005  */
0006 
0007 #ifndef UTILS_LAZY_VAL_H
0008 #define UTILS_LAZY_VAL_H
0009 
0010 namespace kamd
0011 {
0012 namespace utils
0013 {
0014 template<typename F>
0015 class lazy_val
0016 {
0017 public:
0018     lazy_val(F f)
0019         : _f(std::forward<F>(f))
0020         , valueRetrieved(false)
0021     {
0022     }
0023 
0024 private:
0025     F _f;
0026     mutable decltype(_f()) value;
0027     mutable bool valueRetrieved;
0028 
0029 public:
0030     operator decltype(_f())() const
0031     {
0032         if (!valueRetrieved) {
0033             valueRetrieved = true;
0034             value = _f();
0035         }
0036 
0037         return value;
0038     }
0039 };
0040 
0041 template<typename F>
0042 inline lazy_val<F> make_lazy_val(F &&f)
0043 {
0044     return lazy_val<F>(std::forward<F>(f));
0045 }
0046 
0047 } // namespace utils
0048 } // namespace kamd
0049 
0050 #endif // UTILS_LAZY_VAL_H