qxLib
recursive_lambda.h
Go to the documentation of this file.
1 /**
2 
3  @file recursive_lambda.h
4  @author Khrapov
5  @date 3.08.2022
6  @copyright © Nick Khrapov, 2022. All right reserved.
7 
8 **/
9 #pragma once
10 
11 namespace qx
12 {
13 
14 /**
15  @struct recursive_lambda
16  @tparam lambda_t - lambda type
17 **/
18 template<class lambda_t>
20 {
21  lambda_t lambda;
22 
23  template<class... args_t>
24  decltype(auto) operator()(args_t&&... args)
25  {
26  return lambda(*this, std::forward<args_t>(args)...);
27  }
28 
29  template<class... args_t>
30  decltype(auto) operator()(args_t&&... args) const
31  {
32  return lambda(*this, std::forward<args_t>(args)...);
33  }
34 };
35 
36 /**
37  @brief Create lambda that can be called recursively
38  @tparam lambda_t - lambda type: see code example
39  @param lambda - lambda object
40  @retval - lambda that can be called recursively
41 
42  @code
43  auto calc_fibonacci = qx::make_recursive_lambda(
44  [](const auto& calc_fibonacci, int n) -> int // return value is required
45  {
46  if (n == 1 || n == 2)
47  return 1;
48 
49  if (n == 0)
50  return 0;
51 
52  return calc_fibonacci(n - 1) + calc_fibonacci(n - 2);
53  });
54 
55  int nResult = calc_fibonacci(6);
56  @endcode
57 **/
58 template<class lambda_t>
60 {
61  return { std::forward<lambda_t>(lambda) };
62 }
63 
64 } // namespace qx
recursive_lambda< std::decay_t< lambda_t > > make_recursive_lambda(lambda_t &&lambda)
Create lambda that can be called recursively.