Skip to content

Commit 502f5ff

Browse files
Merge pull request #5101 from romainbrenguier/feature/lazy
Add `lazy` function with auto inferred type
2 parents 1b4de42 + d5e6b59 commit 502f5ff

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

src/util/lazy.h

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,4 +43,12 @@ class lazyt
4343
}
4444
};
4545

46+
/// Delay the computation of \p fun to the next time the \c force method
47+
/// is called.
48+
template <typename funt>
49+
auto lazy(funt fun) -> lazyt<decltype(fun())>
50+
{
51+
return lazyt<decltype(fun())>::from_fun(std::move(fun));
52+
}
53+
4654
#endif // CPROVER_UTIL_LAZY_H

unit/util/lazy.cpp

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ Author: Romain Brenguier, [email protected]
99
#include <testing-utils/use_catch.h>
1010
#include <util/lazy.h>
1111

12-
SCENARIO("lazy test", "[core][util][lazy]")
12+
SCENARIO("lazyt::from_fun test", "[core][util][lazy]")
1313
{
1414
std::size_t call_counter = 0;
1515
auto length_with_counter = [&call_counter](const std::string &s) {
@@ -27,3 +27,22 @@ SCENARIO("lazy test", "[core][util][lazy]")
2727
REQUIRE(call_counter == 1);
2828
REQUIRE(result == 3);
2929
}
30+
31+
SCENARIO("lazy test", "[core][util][lazy]")
32+
{
33+
std::size_t call_counter = 0;
34+
auto length_with_counter = [&call_counter](const std::string &s) {
35+
++call_counter;
36+
return s.length();
37+
};
38+
lazyt<std::size_t> lazy_length =
39+
lazy([&] { return length_with_counter("foobar"); });
40+
41+
REQUIRE(call_counter == 0);
42+
auto result = lazy_length.force();
43+
REQUIRE(call_counter == 1);
44+
REQUIRE(result == 6);
45+
result = lazy_length.force();
46+
REQUIRE(call_counter == 1);
47+
REQUIRE(result == 6);
48+
}

0 commit comments

Comments
 (0)